为什么静态成员必须在 main() 之外初始化?
为什么这在 C++ 中无效?
class CLS
{
public:
static int X;
};
int _tmain(int argc, _TCHAR* argv[])
{
CLS::X=100;
return 0;
}
Why is this invalid in C++?
class CLS
{
public:
static int X;
};
int _tmain(int argc, _TCHAR* argv[])
{
CLS::X=100;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们可以在 main 内部更改,就像在您的示例中一样,但是您必须在全局范围内为它们显式分配存储,如下所示:
They can be changed inside of main, like in your example, but you have to explicitely allocate storage for them in global scope, like here:
并不是静态成员必须在全局范围内初始化,而是静态成员必须为其分配存储空间。
It isn't that the static member must be INITIALIZED at global scope, but rather that the static member must have storage allocated for it.
一旦定义了静态数据成员,即使静态数据成员的类的对象不存在,它也存在。在您的示例中,即使已定义静态数据成员 CLS::X,也不存在类 X 的对象。
Once you define a static data member, it exists even though no objects of the static data member's class exist. In your example, no objects of class X exist even though the static data member CLS::X has been defined.
static
成员不是类对象的一部分,但它们仍然是类范围的一部分。它们必须在类外部独立初始化,就像使用类作用域解析运算符定义成员函数一样。static
members aren't part of class object but they still are part of class scope. they must be initialized independently outside of class same as you would define a member function using the class scope resolution operator.