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

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c++ - How can I declare classes that refer to each other?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...