#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'
題外話,但你應該擺脫使用'new'的習慣,當你不需要它,並使用dumb指針,當你需要它的。否則,你最終會花費你的生命來調試內存泄漏,就像你的例子中的那樣,而不是寫有趣的代碼。 –
@MikeSeymour我在這裏學習。如果我放棄使用新的,請你提供一些替代方法嗎? – user2972206
在這種情況下,一個簡單的自動局部變量:'people> aPerson;'當你確實需要動態分配時(因爲對象必須超過創建它的函數),你應該瞭解[RAII](http:// en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization),特別是*智能指針*。 –