【问题标题】:Are "class prototypes" possible in C++?C++ 中是否可以使用“类原型”?
【发布时间】:2014-05-07 16:32:21
【问题描述】:

我正在尝试在 C++ 中实现优先级队列(作为指针堆)。这可能是也可能不是糟糕的设计,但我为堆中的每个节点创建了一个类 PriorityQueue(它将包含整个堆)和另一个类 Node。它看起来像这样:

class PriorityQueue {
    public:
        Node* root;

        void insert(Node* n) {
            n->ancestor = this;
            root->insert(n);
        }
}

class Node {
     public:
         PriorityQueue* ancestor;
         Node* parent, left, right;

         void insert(Node* n) { /* really long insert algorithm */ }
}

这些类相互引用,所以我需要某种原型。我尝试在开头添加class PriorityQueue;class Node;,但由于无效使用不完整类型而出现错误。是否可以按照我想要的方式执行此操作,或者我应该完全改变我的设计?

【问题讨论】:

  • 您在寻找“friend”吗?
  • Node 设为内部类。

标签: c++ class heap priority-queue function-prototypes


【解决方案1】:

让我们忘记术语原型,而专注于前向声明定义

前向声明告诉编译器存在一个类(或结构或联合)和类的名称。而已。这通常在头文件中用于解析参数和返回类型的指针和引用。

编译器需要一个完整的定义,以解析对结构中内容的访问。

【讨论】:

    【解决方案2】:

    “不完整类型的无效使用”的问题是因为您在PriorityQueue 类中定义insert 方法的方式。为了解决这个问题,您需要做的就是将实现移动到声明 Node 之后的位置,如下所示:

    class Node; // <<== I assume that you already have this
    class PriorityQueue {
        public:
            Node* root;
            // At this point, the definition of Node is incomplete.
            // You can declare pointers or references of type Node,
            // but you cannot call its member functions, because the compiler
            // does not know what functions are available for the Node.
            void insert(Node* n);
    }; // <<== Do not forget semicolons
    class Node {
         public:
             PriorityQueue* ancestor;
             Node* parent, left, right;
             void insert(Node* n);
    }; // <<== Do not forget semicolons
    // At this point, C++ compiler knows what functions the Node has,
    // so it lets you make calls of member functions.
    void PriorityQueue::insert(Node* n) {
        n->ancestor = this;
        root->insert(n);
    }
    void Node::insert(Node* n) {
        /* really long insert algorithm */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多