我有两个这样的头文件:
#ifndef LAYER_ONE_TREE_H
#define LAYER_ONE_TREE_H
#include "Utils.h"
#include "LayerTwoTree.h"
class LayerOneTreeNode{
public:
friend class LayerOneTree;
friend class LayerTwoTree;
.
.
.
LayerTwoTree* S_U1;// A pointer to the root of a layerTwoTree
LayerOneTreeNode(){
S_U1 = new LayerTwoTree; //here is the error Error 1 erro C2512: 'LayerTwoTree' : no appropriate default constructor available
S_U1->init();
}
};
class LayerOneTree{
public:
LayerOneTree(){
}
.
.
.
private:
.
.
.
};
#endif
和第二个标题:
#ifndef LAYER_TWO_TREE_H
#define LAYER_TWO_TREE_H
#include "Utils.h"
#include "LayerOneTree.h"
class LayerTwoTreeNode{
public:
friend class LayerTwoTree;
friend class LayerOneTree;
.
.
.
//constructor
LayerTwoTreeNode(Point v = Point(), LayerTwoTreeNode *l = nullptr,
LayerTwoTreeNode *r = nullptr, NodeColor c = Black)
: key(v), color(c), left(l), right(r)
{}
};
class LayerTwoTree{
public:
friend class LayerOneTree;
friend class LayerOneTreeNode;
.
.
.
LayerTwoTree(){
}
LayerOneTreeNode* fatherNode; //the father node of this tree
};
#endif
我不知道为什么我得到"没有合适的默认构造函数错误"我试图在LayerTwoTree
中使用LayerOneTree
时。我认为问题是因为我希望LayerTwoTree
中有LayerOneTree
,LayerOneTree
中有LayerTwoTree
。有什么方法可以解决这个问题吗?如果您需要了解有关代码的更多详细信息,请发表评论。
答案 0 :(得分:2)
假设某些文件包含LayerTwoTree.h,相关的行是:
#ifndef LAYER_TWO_TREE_H
#define LAYER_TWO_TREE_H
#include "LayerOneTree.h"
此时,LayerOneTree.h的内容包含在翻译单元中:
#ifndef LAYER_ONE_TREE_H
#define LAYER_ONE_TREE_H
#include "LayerTwoTree.h"
此时,LayerTwoTree.h的内容再次包含在翻译单元中:
#ifndef LAYER_TWO_TREE_H
#endif
请注意,已经跳过了包含警戒之间的所有内容,因为宏已经定义了!所以,回到LayerOneTree.h:
class LayerOneTreeNode{
public:
friend class LayerOneTree;
friend class LayerTwoTree;
此时,两个树类是声明的,但不完整。
LayerTwoTree* S_U1;// A pointer to the root of a layerTwoTree
创建指向不完整类型的指针是可以的,所以这可行...
LayerOneTreeNode(){
S_U1 = new LayerTwoTree; //here is the error Error 1 erro C2512: 'LayerTwoTree' : no appropriate default constructor available
S_U1->init();
}
...但是此时你正在尝试创建一个这个不完整的类的实例,关于哪个MSC抱怨有一个误导性的错误消息。
使用此架构:
// declare classes
class Foo;
class Bar;
// define classes
class Foo {
Bar* p;
public:
// declare ctor
Foo();
};
class Bar {
Foo* p;
public:
// declare ctor
Bar();
};
// define ctor
Foo::Foo() {
p = new Bar();
}
Bar::Bar() {
p = new Foo();
}
或者,搜索"循环依赖C ++"你会发现更多的解释。