c++相同类型的类成员
我遇到以下情况:
class Foo
{
public:
static const Foo memberOfFoo;
........
}
所以问题是我无法在声明它的同一行中初始化它,并且我无法通过构造函数中的初始化列表初始化它,有人知道该怎么做吗?
I have the following situation:
class Foo
{
public:
static const Foo memberOfFoo;
........
}
So the thing is I can't initialize it in the same line where I declared it, and, I can't initialize it via Initializations List in the constructor, does anyone know what to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后将其放在类定义之外:
这就是
Foo::memberOfFoo
的定义,它可以提供初始化程序并且必须进入.cpp
文件(与任何其他文件一样)其他对象的定义,它在整个程序中只能出现一次,否则会出现链接器错误)。有时您会发现代码没有静态数据成员的定义:
仅当
A::x
从未被取地址且从未传递给引用参数时,省略这样的定义才有效。更正式的说法是:“当 A::x 的所有使用都立即读取 A::x 的存储值时”。许多静态整数常量都是这种情况。Put this outside of the class definition then:
That is the definition of
Foo::memberOfFoo
, which can supply an initializer and has to go into the.cpp
file (like any other definition of objects, it can only appear once in the whole program, otherwise you will get linker errors).Sometimes you will find code that doesn't have definitions for its static data members:
Omitting the definition like that is valid only if
A::x
is never address-taken and never passed to reference parameters. A more formal way to say when it is valid to omit the definition is: "When all uses of A::x immediately read the stored value of A::x". That's the case for many static integer constants.除常量整型类型之外的类静态需要/可以在定义时初始化。您需要通过添加在某处声明您的(不是这样)memberOfFoo
Class statics other than constant integral types need to/can be initialized at the point of definition. You need to declare your (not so)memberOfFoo somewhere, by adding
这就是你如何实现初始化......
This is how you can implement initialization...