简体   繁体   English

C ++:类成员的前向声明(变量)

[英]C++: Forward declaration of class member (variable)

Is it possible to forward declare a class member variable? 是否可以向前声明一个类成员变量? I want to do something like the following (But it doesn't work): 我想做类似以下的事情(但是不起作用):

class myClass;
bool myClass::myvar;

void main()
{
    myClass* aaa;
    ...
    aaa->myvar = false;
}

In this example, myvar is a boolean member of myClass. 在此示例中,myvar是myClass的布尔成员。

No, you can't. 不,你不能。 Imagine the class is scattered across different translation units this way. 想象一下,这种方式将班级分散在不同的翻译单元中。
What members will it have then? 那它将有哪些成员? And what will be the object layout? 对象的布局将是什么?

That's intractable. 太难了

I would recommend to use set/get methods in this case. 我建议在这种情况下使用set / get方法。 Then you don't expose your internal data to the outside world. 这样就不会将内部数据暴露给外界。

In the header of myClass: 在myClass的标题中:

class myClass
{
    public: setMyVar(const bool& value);
    public: inline const bool& getMyVar() const;

    private: bool myVar;
};

In your implementation: 在您的实现中:

class myClass;

void main()
{
    myClass* aaa;
    ...
    aaa->setMyVar(false);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM