【问题标题】:Having attributes of the same class in C++在 C++ 中具有相同类的属性
【发布时间】:2025-12-22 19:10:10
【问题描述】:

我想用 C++ 实现一个通用的树形结构 - 用类! - 这棵树由一个键(在我的例子中是一个整数)和一个 leftChild 和 rightChild 属性组成,它们应该与树本身的类型相同

在 C 中我可以这样做:

typedef struct avl {
    int key;
    int bf;
    struct avl *leftChild;
    struct avl *rightChild;
} AVLTree;

我在我的 C++ 代码中尝试了以下操作:

class MTree {
    public:
        int key;
        int bf;

        MTree leftChild;
        MTree rightChild;

        MTree() {}
        ~MTree() {};
 }

但它不起作用,它给了我以下错误消息:

mtree-ops.cpp:12: error: field ‘leftChild’ has incomplete type

mtree-ops.cpp:13: error:error: field ‘rightChild’ has incomplete type

所以你看,看起来我不能说我的类有它自己类型的属性,因为这就像试图引用在定义时并不真正存在的东西。使用 C++ 类如何做到这一点?

【问题讨论】:

    标签: c++ class object data-structures


    【解决方案1】:

    (我还不能发布 cmets。)

    简而言之,MTree leftChild 将有两个自己的 MTree 孩子,每个孩子都有两个孩子,依此类推。因此,MTree 对象将无限大,因为它们将包含无限多个 MTree 实例。

    参见this question,它本质上是相同的。正如那里所提到的,您必须求助于对子对象的引用或指针,从而为单个 MTree 对象提供有限大小。例如,

    class MTree
    {
    [...]
    public:
        MTree* leftChild;
        MTree* rightChild;
    };
    

    (您可以将MTree* 替换为MTree&。)

    【讨论】:

      【解决方案2】:

      这是 C++11 的惯用方法:

      #include <memory>
      class MTree {
        public:
          int key;
          int bf;
      
          std::unique_ptr<MTree> leftChild;
          std::unique_ptr<MTree> rightChild;
      
          MTree():key(0), bf(0) {}
          ~MTree() {};
      };
      

      std::unique_ptr 是一个开销接近于零的智能指针,它表示包含 struct 的指针拥有所有权,它可以是 nullptr

      要添加孩子,只需leftChild.reset( new MTree );

      当一个父级被销毁时,它的所有子级都被自动销毁。如果您想从父母那里带走孩子,请执行std::unique_ptr&lt;MTree&gt; branch = std::move( parent.leftChild );,它声称对左孩子的所有权并将其从父母手中移除。

      如果您只想要一个非拥有指针,请使用parent.leftChild.get()。如果你想访问左孩子的keyparent.leftChild-&gt;key 就可以了(注意:你负责检查nullptr

      【讨论】:

        【解决方案3】:

        我认为你的代码应该是这样的

        class MTree {
            public:
                int key;
                int bf;
        
                MTree * leftChild;
                MTree * rightChild;
        
                MTree() {}
                ~MTree() {};
        }
        

        【讨论】:

          最近更新 更多