我有两个这样的头文件:

#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

第二个 header :
#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。有什么办法可以解决这个问题?如果您需要了解有关代码的更多详细信息,请发表评论。

最佳答案

分析:

假设一些文件包含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/

10-11 16:20