문제

Made this simple class with MSVC++ 6.0

class Strg
{
public:
    Strg(int max);
private:
    int _max;
};


Strg::Strg(int max)
{
  _max=max;
}

Sounds good if I use it in :

main()
{
  Strg mvar(10);
}

But Now If I use it in an another class :

class ok
{
public:
    Strg v(45);
};

I get message error : error C2059: syntax error : 'constant'

Could you tell me more please ?

올바른 솔루션이 없습니다

다른 팁

Should be:

class ok
{
public:
    Strg v;
    ok() : v(45) {}
};

Non-static member variables that don't have default constructors (v in this case) should be initialized using initialization lists. In functions (like main) on the other hand you can use the regular constructor syntax.

What the compiler is complaining about is that you are trying to provide instruction on how ton instantiate the class member v inside your class definition, which is not allowed.

The place to instantiate v would be inside the contructor, or in the constructor's initializer list. For example:

Inside constructor:

class ok
{
public:
    Strg v;
    ok() {
        v = Strg(45);
    }
};

In initializer list:

class ok
{
public:
    Strg v;
    ok() : v(45) {}
};

The correct way to do it is the last one (otherwise, v would also require a default constructor and would be initialized twice).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top