VC++6 error C2059: syntax error : 'constant

2020-03-26 03:23发布

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 ?

2条回答
你好瞎i
2楼-- · 2020-03-26 04:02

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).

查看更多
神经病院院长
3楼-- · 2020-03-26 04:17

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.

查看更多
登录 后发表回答