开发者

Reciprocal friend member functions = circular include declarations

I have two classes defined in different h files and each class has some private functions. However, there's one function in each class that I want to be able to access from a function in the other class.

For example...

//apple.h:

class Beets;

class Apple
{
public:
    double  ShadeUsed();
private:
    void    Fruit();
    bool    RedRoots();
    friend  bool Beets::BlueRoots(); //<--- Error b/c not declared yet
};


//beets.h
#include "apple.h"

class Beets
{
    public:
    double  SunNeeded();
private:
    void    Leaves();
    bool    BlueRoots();
    friend  bool Apple::RedRoots();
};

The goal is that only one function in each class should have access to the other classes private stuff. For example, only the root function should have access to the other class's private stuff. However, without the includes becoming circul开发者_JAVA技巧ar I cannot achieve reciprocal friendship.

I've considered making for example, the whole Beets class a friend to Apples that way the class pre-declaration would be enough, but I'd rather only allow one function private access.

Any suggestions? Thanks in advance, Matt.

(P.S. why does carriage return between each of "Thanks in advance,", "Matt" not result in newlines?)


You could use friend functions which call the member functions.

//apple.h:

class Beets;

class Apple
{
public:
    double  ShadeUsed();
private:
    void    Fruit();
    bool    RedRoots();
    friend  bool Beets_BlueRoots(Beets* beets); 
    friend  bool Apple_RedRoots(Apple* apple);
};

bool Apple_RedRoots(Apple* apple);


//beets.h

class Beets
{
    public:
    double  SunNeeded();
private:
    void    Leaves();
    bool    BlueRoots();
    friend  bool Apple_RedRoots();
    friend  bool Beets_BlueRoots(Beets* beets);
};

bool Beets_BlueRoots(Beets* beets);


It appears that you've got some design issue. I would suggest inheritance:

class A{
public:
   virtual bool Roots();
}
class Apples : public A
{}
class Beets : public A
{}

Now, both Apples and Beets have Roots function, without circular includes, and it's public so they can access each other (and the only one public, so you're safe). You don't even need to know if the roots are red or blue. And if you create a "Carrot" class later on, your classes wouldn't need to change to include the "OrangeRoots" as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜