初始化静态变量时出现语法错误
定义了两个类..
class Dictionary
{
public:
Dictionary();
Dictionary(int i);
// ...
};
但
class Equation
{
static Dictionary operator_list(1);
// ...
};
问题是,每当我编译它时,我都会收到一条奇怪的错误消息
错误 C2059:语法错误:“常量”
但是当我在operator_list上使用默认构造函数时它编译得很好。
There are two classes defined..
class Dictionary
{
public:
Dictionary();
Dictionary(int i);
// ...
};
and
class Equation
{
static Dictionary operator_list(1);
// ...
};
but the problem is, whenever I compile this, I get a weird error message
error C2059: syntax error : 'constant'
But it compiles well when I use the default constructor on operator_list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,不能将声明和初始化结合起来。当您没有指定
operator_list
的构造函数参数时,您不会调用它的默认构造函数:您只需声明它即可。您还需要在相应的 C++ 文件中对其进行初始化,如下所示:Equation.h
Equation.cpp:
请注意 CPP 文件中缺少
static
:它不是有意设计的。编译器已经从声明中知道operator_list
是静态的。编辑:您可以选择整数和枚举类型的静态常量成员:您可以在 CPP 文件中初始化它们,如上例所示,或者您可以在标头中给它们一个值。您仍然需要在 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.cpp:
Note the absence of
static
in the CPP file: it is not there by design. The compiler already knows from the declaration thatoperator_list
is static.Edit: 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.
static Dictionary operator_list();
是一个函数签名,声明一个返回Dictionary
且不带任何参数的函数,这就是编译器允许您这样做的原因。static Dictionary operator_list(1);
失败的原因是您无法在类的声明中设置复杂类型的值。您需要在其他地方执行此操作(例如在 .cpp 中)有关更多信息,请参阅这篇文章: https://stackoverflow.com/a /3792427/103916
static Dictionary operator_list();
is a function signature declaring a function returning aDictionary
and taking no arguments, that's why your compiler let you do it.The reasons
static Dictionary operator_list(1);
fails is because you can't set a value of an complex type in the declaration of your classes. You need to do this elsewhere (e.g. in the .cpp )For more information, see this post : https://stackoverflow.com/a/3792427/103916
输出是:
Output is: