C++ 两个相互引用的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/994253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two classes that refer to each other
提问by sean e
I'm new to C++, so this question may be basic:
我是 C++ 新手,所以这个问题可能是基本的:
I have two classes that need to refer to each other. Each is in its own header file, and #include's the other's header file. When I try to compile I get the error "ISO C++ forbids declaration of ‘Foo' with no type" for one of the classes. If I switch things so the opposite header gets parsed first I get the same error with the other class.
我有两个需要相互引用的类。每个都在自己的头文件中,#include 是另一个的头文件。当我尝试编译时,对于其中一个类,出现错误“ISO C++ 禁止声明没有类型的‘Foo’”。如果我切换事物以便首先解析相反的标头,我会在另一个类中得到相同的错误。
Is it possible in C++ to have two classes that need references to each other?
在 C++ 中是否有可能有两个需要相互引用的类?
For more detail: I have an "App" class and a "Window" class. App needs to refer to Window to make the window. Window has a button that calls back to App, so it needs a reference to App. If I can't have two classes refer to each other, is there a better way to implement this?
有关更多详细信息:我有一个“App”类和一个“Window”类。App需要参考Window来制作窗口。Window有一个回调App的按钮,所以需要一个App的引用。如果我不能让两个类相互引用,有没有更好的方法来实现这一点?
回答by sean e
You can use forward declarations in the header files to get around the circular dependencies as long as you don't have implementation dependencies in the headers. In Window.h, add this line:
只要头文件中没有实现依赖,就可以在头文件中使用前向声明来绕过循环依赖。在 Window.h 中,添加以下行:
class App;
In App.h, add this line:
在 App.h 中,添加以下行:
class Window;
Add these lines before the class definitions.
在类定义之前添加这些行。
Then in the source files, you can include the headers for the actual class definitions.
然后在源文件中,您可以包含实际类定义的头文件。
If your class definitions reference members of the other class (for example, in inlines), then they need to be moved to the source file (no longer inline).
如果您的类定义引用其他类的成员(例如,内联),则需要将它们移动到源文件(不再内联)。
回答by aJ.
Forward declaration is the way to go.
前向声明是要走的路。
If you are using pointers\reference in class header then Forward declaration at both sides would work for you.
如果您在类头中使用指针\引用,那么双方的前向声明都适合您。
If you are creating the object as a class member then you must include header itself. ( Forward declaration won't work as compiler needs class definition for knowing the size).
如果您将对象创建为类成员,则必须包含标头本身。(前向声明不起作用,因为编译器需要类定义来了解大小)。
Refer C++ FAQ for solving such senario:
If you are creating the Window as member then include the Window header in App but at the same time Window shouldn't include the App's header. Use the combination of pointer to App and the forward declaration there.
如果您将 Window 创建为成员,则在 App 中包含 Window 标头,但同时 Window 不应包含 App 的标头。使用指向 App 的指针和那里的前向声明的组合。
回答by Matthew Flaschen
You need a forward declaration.
您需要提前声明。