初始化静态变量时的语法错误 [英] Syntax error when initializing a static variable
问题描述
有两个类定义..
class Dictionary
{
public:
Dictionary();
Dictionary(int i);
// ...
};
和
class Equation
{
static Dictionary operator_list(1);
// ...
};
但问题是,每当我编译这个,我得到一个奇怪的错误信息
but the problem is, whenever I compile this, I get a weird error message
错误C2059:语法错误:'constant'
error C2059: syntax error : 'constant'
它编译好,当我使用默认构造函数在operator_list。
But it compiles well when I use the default constructor on operator_list.
推荐答案
在C ++中,不能结合声明和初始化。当不指定 operator_list
的构造函数参数时,不会调用其默认构造函数:您只需声明它。您还需要在相应的C ++文件中初始化它,如下所示:
In C++ you cannot combine declaration and initialization. When you do not specify constructor parameters of operator_list
, you do not call its default constructor: you simply declare it. You need to also initialize it in the corresponding C++ file, like this:
Equation.h
Equation.h
class Equation {
static Dictionary operator_list;
};
Equation.cpp:
Equation.cpp:
Dictionary Equation::operator_list(1);
注意CPP中没有 static
文件:它不是通过设计。编译器已经从声明中知道 operator_list
是静态的。
Note the absence of static
in the CPP file: it is not there by design. The compiler already knows from the declaration that operator_list
is static.
编辑:的积分和枚举类型:您可以在CPP文件中初始化它们,如上面的例子,或者你可以给他们一个值在标题。您仍然需要在C ++文件中定义该成员,但是在定义时不能给它一个值。
You have a choice with static constant members of integral and enumerated types: you can initialize them in the CPP file as in the example above, or you can give them a value in the header. You still need to define that member in your C++ file, but you must not give it a value at the definition time.
这篇关于初始化静态变量时的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!