我只是在学习模板,在我尝试使用该模板时,我遇到了类模板和调用成员函数之间的错误。
班级模板
template<class T> class MyVector{
private:
int dataMembers;
public:
template<class T>
void MyVector<T>::push_back(){//body of the function}
};
驱动程序
int main()
{
MyVector<Account*> bankAccounts;
bankAccounts.push_back(//dynamic object);
//error: class MyVector<Account*> has no member "push_back"
//...
return 0;
}
答案 0 :(得分:2)
您可以在类中声明和定义模板函数,如下所示:
template<class T>
class MyVector {
private:
int dataMembers;
public:
void push_back( T arg ) {
//some code
}
};
或者在外面定义身体:
template<class T>
class MyVector {
private:
int dataMembers;
public:
void push_back( T arg );
};
template<class T>
void MyVector<T>::push_back( T arg ) {
//some code
}