简体   繁体   中英

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.

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. Then you don't expose your internal data to the outside world.

In the header of 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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