Why is a class allowed to have a static member of itself, but not a non-static member?

大兔子大兔子 提交于 2019-12-28 03:01:27

问题


class base {
public:
    base a;
};

It gives compilation error.

class base {
public:
    static base a;
};

whereas this code does not give compilation error


回答1:


Because static class members are not stored in the class instance, that's why a static 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.




回答2:


I'm guessing the error is something like

field ‘a’ has incomplete type

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.



来源:https://stackoverflow.com/questions/8517609/why-is-a-class-allowed-to-have-a-static-member-of-itself-but-not-a-non-static-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!