gpt4 book ai didi

c++ - 错误 C2512 : 'LayerTwoTree' : no appropriate default constructor available

转载 作者:行者123 更新时间:2023-11-30 03:59:47 26 4
gpt4 key购买 nike

我有两个像这样的头文件:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com