我无法在C++中使用模板进行编译

fre*_*ara 2 c++ templates

我用g ++编译了下面的电线

#include <iostream>
#include <string>
using namespace std;
template<class T>
class Node<const char*>{
private:
  string x_;
  Node* next_;
public:
  Node (const char* k, Node* next):next_(next),x_(k){}
  string data(){return x_;}
  Node *get_next(){return next_;}
};

$ g++ -c node01.cc
node01.cc:5: error: ‘Node’ is not a template
Run Code Online (Sandbox Code Playgroud)

怎么了?我是c ++的先生

Tod*_*lin 6

你混淆了声明和实例.声明模板时,不要在其名称后面立即指定类型.相反,声明如下:

template<class T>
class Node {
private:
  const T x_;
  Node *next_;
public:
  Node (const T& k, Node *next) : x_(k), next_(next) { }
  const T& data(){return x_;}
  Node *get_next(){return next_;}
};
Run Code Online (Sandbox Code Playgroud)

您的原始声明也会混淆string,const char *以及应该遵循的泛型类型T.对于这样的模板,您可能希望让用户定义成员的类型(x_).如果您明确地将其声明为const char *string,则通过限制用户可以使用的内容来失去通用性T.

请注意,我改变了类型的实例变量,构造器和返回类型的参数data()是来讲T,太.

实际实例化模板类型的变量时,可以提供具体的类型参数,例如:

int main(int argc, const char **argv) {
    Node<char*> *tail = new Node<char*>("tail", NULL);
    Node<char*> *node = new Node<char*>("node", tail);
    // do stuff to mynode and mytail
}
Run Code Online (Sandbox Code Playgroud)

每当您Node在模板声明之外编写模板名称时,在您为参数提供值之前,它都不会完成T.如果你只是说Node,编译器将不知道你想要什么的节点.

上面的内容有点冗长,所以当你实际使用它时,你也可以用typedef简化它:

typedef Node<char*> StringNode;
int main(int argc, const char **argv) {
    StringNode *tail = new StringNode("tail", NULL);
    StringNode *node = new StringNode("node", tail);
    // do stuff to mynode and mytail
}
Run Code Online (Sandbox Code Playgroud)

现在,您已经构建了两个节点的链接列表.您可以使用以下内容打印出列表中的所有值:

for (StringNode *n = node; n; n = n->get_next()) {
    cout << n->data() << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果一切顺利,这将打印出来:

node
tail
Run Code Online (Sandbox Code Playgroud)