作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个像这样的头文件:
#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
我不知道为什么当我尝试在我的 LayerOneTree
中使用 LayerTwoTree
时出现“没有合适的默认构造函数可用错误”。我认为问题是因为我想在 LayerOneTree
中有一个 LayerTwoTree
并且在我的 LayerTwoTree
中有一个 LayerOneTree
。有什么办法可以解决这个问题吗?如果您需要了解有关代码的更多详细信息,请发表评论。
最佳答案
假设一些文件包含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++”,您会找到更多解释。
关于c++ - 错误 C2512 : 'LayerTwoTree' : no appropriate default constructor available,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26743216/
我有两个像这样的头文件: #ifndef LAYER_ONE_TREE_H #define LAYER_ONE_TREE_H #include "Utils.h" #include "LayerTwo
我是一名优秀的程序员,十分优秀!