我用 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
怎么了? 我是 C++ 的初学者
最佳答案
您混淆了声明和实例化。声明模板时,不会在其名称后立即指定类型。相反,像这样声明它:
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_;}
};
你原来的声明也混淆了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
}
每当你写模板名称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
}
现在您已经构建了一个包含两个节点的链表。您可以打印出列表中的所有值,如下所示:
for (StringNode *n = node; n; n = n->get_next()) {
cout << n->data() << endl;
}
如果一切顺利,这将打印出:
node
tail
关于c++ - 我无法在 C++ 中使用模板进行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1046930/