开发者

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

开发者 https://www.devze.com 2023-02-01 03:17 出处:网络
Made this simple class with MSVC++ 6.0 class Strg { public: Strg(int max); private: int _max; }; Strg::Strg(int max)

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()
{
 开发者_StackOverflow 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消