2013-11-09 136 views
3
#include <iostream> 
using namespace std; 

template<class T> 
class people{ 
    public: 
    virtual void insert(T item)=0; 
    virtual T show(T info)=0; 
}; 

template<class T> 
class name 
{ 
    private: 
    T fname; 
    T lname; 
    public: 
     name(T first, T last); 
    // bool operator== (name & p1, name &p2) 
}; 
template <class T> 
name<T>::name(T first, T last){ 
    fname = first; 
    lname = last; 
} 
template <class T> 
class person : public people<T> 
{ 
    private: 
    T a[1]; 
    int size; 
    public: 
    person(); 
    virtual void insert(T info); 
    virtual T show(); 
}; 
template<class T> 
person<T>::person(){ 
    size = 0; 
} 
template<class T> 
void person<T>::insert(T info){ 
    a[0] =info; 
} 
template<class T> 
T person<T>::show(){ 
     return a[0]; 
} 
int main(){ 
    string first("Julia"), last("Robert"); 
    name<string> temp(first,last); 
    people<name>* aPerson = new person(); 
    aPerson-> insert(temp); 
    aPerson->show(); 
    return 0; 
} 

这些都是我不断收到错误,我无法找出真正的问题是:C++类型/值不匹配

test.cpp:52: error: type/value mismatch at argument 1 in template parameter list for 'template<class T> class people' 
test.cpp:52: error: expected a type, got 'name' 
test.cpp:52: error: invalid type in declaration before '=' token 
test.cpp:52: error: expected type-specifier before 'person' 
test.cpp:52: error: expected ',' or ';' before 'person' 
test.cpp:53: error: request for member 'insert' in '* aPerson', which is of non-class type 'int' 
test.cpp:54: error: request for member 'show' in '* aPerson', which is of non-class type 'int' 
+0

题外话,但你应该摆脱使用'new'的习惯,当你不需要它,并使用dumb指针,当你需要它的。否则,你最终会花费你的生命来调试内存泄漏,就像你的例子中的那样,而不是写有趣的代码。 –

+0

@MikeSeymour我在这里学习。如果我放弃使用新的,请你提供一些替代方法吗? – user2972206

+0

在这种情况下,一个简单的自动局部变量:'people > aPerson;'当你确实需要动态分配时(因为对象必须超过创建它的函数),你应该了解[RAII](http:// en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization),特别是*智能指针*。 –

回答

5

name是一个模板类,所以你必须指定模板:

people<name<string>>* aPerson = new person<name<string>>(); 
+2

@ user2972206不客气!如果你将这个问题标记为“已解决”,它会帮助其他人。 – yizzlez

+0

这段代码最终会出现编译器错误:'>>'在嵌套模板参数列表中应该是'>>' –