求c++自定义模板类的用法

来源:百度知道 编辑:UC知道 时间:2024/05/25 14:08:03
请教C++高手怎么把下面的模板类的成员函数定义在类外?
#include<iostream>
using namespace std;
template<class T1,class T2>
class mytemp
{
private:
T1 t1;
T2 t2;
public:
mytemp(T1 tt1,T2 tt2)
{
t1=tt1;
t2=tt2;
}
~mytemp()
{}
void display()
{cout<<t1<<endl<<t2<<endl;}
};
int main()
{
int a=123;
double b=123.123;
mytemp<int,double> mt(a,b);
mt.display();
return 0;
}

#include<iostream>
using namespace std;
template<class T1,class T2>
class mytemp
{
private:
T1 t1;
T2 t2;
public:
mytemp(T1 tt1,T2 tt2);
~mytemp();
void display();
};

template<class T1,class T2>
mytemp::mytemp(T1 tt1,T2 tt2)
{
t1=tt1;
t2=tt2;
}

mytemp::~mytemp()
{}

void mytemp::display()
{cout<<t1<<endl<<t2<<endl;}
int main()
{
int a=123;
double b=123.123;
mytemp<int,double> mt(a,b);
mt.display();
return 0;
}

因为你在类中定义了t1,t2两个对象,为T1,T2类型的.如果没有template<class T1,class T2>这个带参数T1,T2的类模板声明的话,则不能定义t1,t2.除非模板在类mytemp前先定义. 以c++我自学了好几年了.

因为你已经将t1 t2定义为class mytemp的私有变量,成员函数若想定义在类外则无法访问t1 和t2