【问题标题】:c++ template no appropriate default constructor [duplicate]c ++模板没有适当的默认构造函数[重复]
【发布时间】:2012-10-11 13:17:44
【问题描述】:

可能重复:
Why should the implementation and the declaration of a template class be in the same header file?

希望你能帮助我。

我知道这个问题(在进行谷歌搜索后)已被问过数百万次。我确信我的问题的解决方案是在这数百万个问题中的一个,但我找不到它所以我决定问。

我特别收到了这个错误:

错误 1 ​​错误 C2512: 'NodeQueue' : 没有合适的默认构造函数可用 a:\work\fast\semi 5\automata\assignments\progass1\progass1\progass1\tree.h 33 1 progass1

具体行有这样的定义:

level=new NodeQueue<Node>;

下一行也出现同样的错误,但原因是一样的..

我有所有不知道为什么会发生这种情况的默认构造函数。以下是部分代码:

头文件的顶部:

#include <iostream>
using namespace std;

#include "intarr.h"
class Node;
template <typename t>
class QueueNode;

template <typename t>
class NodeQueue;

树:

class Tree{

    Node* root;


    int level_length;
    Node* curr;
    NodeQueue <Node>* level,*level_bak;
public:

    Tree(){
        root=NULL;
        level_length=0;
        curr=NULL;
        level=new NodeQueue<Node>;
        level_bak=new NodeQueue<Node>;
    }
// I doubt you need the rest...

类节点

class Node{
public:
    Node *top,*right,*bottom,*left,*prev;
    Node *a,*b,*c;
    int row,col;
    Node(){

    }
    Node(int x,int y){
        top=right=bottom=left=prev=NULL;
        row=x;col=y;
        a=b=c=NULL;
    }

};

queuenode(即队列的节点)

 template <typename t>
     class QueueNode {
     public:
        QueueNode* next;
        QueueNode* prev;

        t *value;
        QueueNode(){

        }
        QueueNode(t* value){
            next=NULL;
            this->value=value;
        }

    };

节点队列:

 template <typename t>
 class NodeQueue {
    QueueNode *head;
    QueueNode *tail;

    //lhs=bottom;

 public:
     NodeQueue(){
        head=NULL;
        tail=NULL;
    }
//....... rest of the code you dont need

【问题讨论】:

  • 你所拥有的只是不是一个最小的例子。为了练习起见,试着编造最小的例子来说明你的问题。 (应该是六行左右。)这将帮助您发现错误并在将来提出更好的问题。
  • @kerrek,它们位于单个标头类中。一切都在标题类中。我会尽量减少代码
  • 对于初学者,您不需要在NodeQueue的定义中指定QueueNode&lt;t&gt;吗?
  • 卢奇安得到了答案:)....

标签: c++ templates visual-c++


【解决方案1】:

由于这是一个编译器错误(不是链接器,就像大多数模板错误问题一样),我猜这是因为您前向声明了类型:

template <typename t>
class NodeQueue;

为什么要前向声明它而不是包含文件?要构造一个对象,您需要完整的定义,所以 #include "NodeQueue.h".

在不需要完整类型的情况下使用前向声明。

【讨论】:

  • 是的,这成功了。我只是删除了它,因为所有内容都在一个头文件中。谢啦。但是前向声明到底是什么意思?
  • @death_relic0 前向声明的话题太大,无法在评论中讨论(希望您理解)。由于它是一个重要的语言方面,我建议你谷歌。
【解决方案2】:

根据 MSDN Compiler Error C2512,当您尝试创建不完整的类实例时也会生成 - 前向声明,但完整定义不可用。

因此您需要将NodeQueue 定义标头包含在tree.h 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 2021-09-02
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多