简体   繁体   English

VC ++ 6错误C2059:语法错误:'常量'

[英]VC++6 error C2059: syntax error : 'constant'

Made this simple class with MSVC++ 6.0 用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' 我收到消息错误: 错误C2059:语法错误:'常量'

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 . 应使用初始化列表初始化没有默认构造函数(在本例中为v)的非静态成员变量。 In functions (like main) on the other hand you can use the regular constructor syntax. 另一方面,在函数(如main)中,您可以使用常规构造函数语法。

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. 编译器抱怨的是你试图提供如何在类定义中实例化类成员v指令,这是不允许的。

The place to instantiate v would be inside the contructor, or in the constructor's initializer list. 实例化v的地方将在构造函数内部或构造函数的初始化列表中。 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). 正确的方法是最后一个(否则, v也需要一个默认的构造函数,并将被初始化两次)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM