Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It's been a long time since I've done C++ and I'm running into some trouble with classes referencing each other.

Right now I have something like:

a.h

class a
{
  public:
    a();
    bool skeletonfunc(b temp);
};

b.h

class b
{
  public:
    b();
    bool skeletonfunc(a temp);
};

Since each one needs a reference to the other, I've found I can't do a #include of each other at the top or I end up in a weird loop of sorts with the includes.

So how can I make it so that a can use b and vice versa without making a cyclical #include problem?

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to use Forward Declaration:

a.h

class b;
class a
{
  public:
    a();
    bool skeletonfunc(b temp);
}

However, in many situations, this can force you to work with references or pointers in your method calls or member variables, since you can't have the full types in both class headers. If the size of the type must be known, you need to use a reference or pointer. You can, however, use the type if only a method declaration is required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...