简体   繁体   中英

Forward declaration of two dependend classes with friend function

I have two classes. One depends on the other class and the other one contains a function that is friend to the first class. There's a lot of other stuff in this classes but this is what it boils down to:

class LightBase;

class Color
{
    friend void LightBase::UpdateColor();
};

class LightBase
{
    public:
        void UpdateColor();
    protected:
        std::vector<Color> colors_;
};

But apparently my forward declaration is not correct. I get this:

error: invalid use of incomplete type 'class LightBase'

I get that UpdateColor() is not known by the time the friend declaration is made. But how do I fix it?

It will work fine if you will change the arrangement a bit:

class Color;

class LightBase {
    public:
        void UpdateColor();
    protected:
        // Color has been declared
        std::vector<Color> colors_; 
};

class Color {
    // LightBase has been defined
    friend void LightBase::UpdateColor();
};

As to the use of LightBase::UpdateColor , we need to have LightBase class defined to use its function member LightBase , Since it is not known until then, as you pointed out yourself.

Meanwhile, we can have a std::vector<Color> with Color not being defined yet, only declared in the scope.

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