Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...