問題描述
我希望創建兩個類,每個類都包含另一個類類型的對象.我怎樣才能做到這一點?如果我不能這樣做,是否有解決方法,例如讓每個類都包含一個指向其他類類型的指針?謝謝!
I'm looking to create two classes, each of which contains an object of the other class type. How can I do this? If I can't do this, is there a work-around, like having each class contain a pointer to the other class type? Thanks!
這是我所擁有的:
文件:bar.h
#ifndef BAR_H
#define BAR_H
#include "foo.h"
class bar {
public:
foo getFoo();
protected:
foo f;
};
#endif
文件:foo.h
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class foo {
public:
bar getBar();
protected:
bar b;
};
#endif
文件:ma??in.cpp
#include "foo.h"
#include "bar.h"
int
main (int argc, char **argv)
{
foo myFoo;
bar myBar;
}
$ g++ main.cpp
In file included from foo.h:3,
from main.cpp:1:
bar.h:6: error: ‘foo’ does not name a type
bar.h:8: error: ‘foo’ does not name a type
推薦答案
你不能讓兩個類直接包含另一種類型的對象,否則你需要為對象提供無限空間(因為 foo 有一個 barfoo 有一個酒吧等)
You cannot have two classes directly contain objects of the other type, since otherwise you'd need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.)
不過,您確實可以通過讓兩個類存儲彼此的指針來做到這一點.為此,您需要使用前向聲明,以便兩個類知道彼此的存在:
You can indeed do this by having the two classes store pointers to one another, though. To do this, you'll need to use forward declarations so that the two classes know of each other's existence:
#ifndef BAR_H
#define BAR_H
class foo; // Say foo exists without defining it.
class bar {
public:
foo* getFoo();
protected:
foo* f;
};
#endif
和
#ifndef FOO_H
#define FOO_H
class bar; // Say bar exists without defining it.
class foo {
public:
bar* getBar();
protected:
bar* f;
};
#endif
請注意,兩個標頭不包含彼此.相反,他們只是通過前向聲明知道另一個類的存在.然后,在這兩個類的 .cpp 文件中,您可以#include
另一個標題來獲取有關該類的完整信息.這些前向聲明可以讓你打破foo需要bar需要foo需要bar"的引用循環.
Notice that the two headers don't include each other. Instead, they just know of the existence of the other class via the forward declarations. Then, in the .cpp files for these two classes, you can #include
the other header to get the full information about the class. These forward declarations allow you to break the reference cycle of "foo needs bar needs foo needs bar."
這篇關于如何在 C++ 中創建兩個相互用作數據的類?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!