对于下面的代码:
#include <iostream>
#include <string>
using namespace std;
class Foo2;
class Foo3;
template <class T>
class Foo1 {
public:
Foo1();
void print() {
cout << "My name is: " << name << endl;
}
T getNext(){
return nextLink;
}
string name;
T nextLink;
};
class Foo2 : public Foo1 {
public:
Foo2(){
name = "Foo2";
}
};
class Foo3 : public Foo1 {
public:
Foo3(){
name = "Foo3";
}
};
template <class T>
class LinkedList {
public:
T curr;
T first;
void add(T node){
if(first == NULL){
first = node
}
node->nextLink = this;
curr = node;
}
T getNext(){
return next;
}
void printAll(){
T curr = first;
cout << "Contents are: " ;
while(curr != NULL){
cout << curr.print() << ", ";
curr = curr.getNext();
}
}
};
int main() {
LinkedList<?> list;
list.add(new Foo2());
list.add(new Foo3());
list.printAll();
return 0;
}
我正在尝试实现一个通用链表,我意识到我可以导入<list>
但这不适合我的项目。我正在尝试创建一个链接列表Foo2
and Foo3
对象 - 以上是我能完成的最好的事情,因为我是 C++ 新手。
Error:
generic.C: In instantiation of Foo1<Foo2>:
generic.C:26: instantiated from here
generic.C:22: error: Foo1<T>::nextLink has incomplete type
generic.C:6: error: forward declaration of âclass Foo2
generic.C: In instantiation of Foo1<Foo3>:
generic.C:34: instantiated from here
generic.C:22: error: Foo1<T>::nextLink has incomplete type
generic.C:7: error: forward declaration of class Foo3
generic.C: In member function void LinkedList<T>::add(T):
generic.C:50: error: expected ; before } token
generic.C: In member function T LinkedList<T>::getNext():
generic.C:55: error: ânextâ was not declared in this scope
generic.C: In function âint main()â:
generic.C:69: error: template argument 1 is invalid
generic.C:69: error: invalid type in declaration before â;â token
generic.C:70: error: request for member âaddâ in âlistâ, which is of non-class type âintâ
generic.C:71: error: request for member âaddâ in âlistâ, which is of non-class type âintâ
generic.C:72: error: request for member âprintAllâ in âlistâ, which is of non-class type âintâ
你需要使用 T*,而不是 T。在我看来,你来自 Java,其中一切都是引用。没有?
在 C++ 模板中。我认为你需要先拿起一本关于基础 C++ 的书,然后再回到模板。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)