为什么类可以有自己的静态成员,但不能有非静态成员?
class base {
public:
base a;
};
它给出编译错误。
class base {
public:
static base a;
};
而这段代码不会给出编译错误
class base {
public:
base a;
};
It gives compilation error.
class base {
public:
static base a;
};
whereas this code does not give compilation error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
static
类成员不存储在类实例中,这就是static
可以工作的原因。将一个对象存储在另一个相同类型的对象中会破坏运行时 - 无限大小,对吗?
sizeof
会返回什么?编译器需要知道对象的大小,但由于它包含相同类型的对象,因此没有意义。Because
static
class members are not stored in the class instance, that's why astatic
would work.Storing an object inside another object of the same type would break the runtime - infinite size, right?
What would
sizeof
return? The size of the object needs to be known by the compiler, but since it contains an object of the same type, it doesn't make sense.我猜错误是这样的
这是因为当非静态时,类
A
直到右大括号才完全定义。另一方面,静态成员变量在类完全定义后需要单独的定义步骤,这就是它们起作用的原因。搜索声明和定义之间的区别以获得更彻底的解释。
I'm guessing the error is something like
This is because when not static, the class
A
is not fully defined until the closing brace. Static member variables, on the other hand, need a separate definition step after the class is fully defined, which is why they work.Search for the difference between declaration and definition for more thorough explanations.