c++ 模板类外定义构造成员模板

2025-03-01 03:12:06
推荐回答(3个)
回答1:

检查你的语法是不是有错
另外,所谓的“拿出来”,应该只能拿到头文件里,而不能放进cpp文件
这个是编译器的限制,模板定义的实体也要放在头文件而不是cpp

拿出来应该这么写:
template

int TwoNum::compate(){ //比较a和b的大小
if(a>b) return 1;
else if(a==b) return 0;
else return -1;
}

回答2:

#include "iostream.h"
template //Type为参数类型
class TwoNum
{ //由2个Type类型的数据成员构成的模板
Type a;
Type b;
public:
Type maximun()
{ //返回最大值
return (a>b)?a:b;
}

Type minimun()
{
return (a>b)?b:a;
}

void set(Type& aa,Type& bb)
{ //赋值
a==aa;b==bb;
}

TwoNum(Type aa,Type bb);//在此声明
int compate();
Type geta(){return a;}
Type getb(){return b;}
};

template
TwoNum::TwoNum(Type aa=0,Type bb=0):a(aa),b(bb)
{

}
//比较a和b的大小
template
int TwoNum::compate()
{
if(a>b) return 1;
else if(a==b) return 0;
else return -1;
}

void main()
{
TwoNum x(4,8);
cout< char ch='x';
//TwoNum y(ch,'x');
//cout< //Franction f1(5,4),f2(4,5);
//TwoNum a(f1,f2);
//cout<}

你的编程风格不好。希望可以适当改革。。。

回答3:

把错误提示贴出来,另外,在类外定义的时候,有没有在类内部先申明?
类定义放在头文件中,类函数实现放在.cpp文件中。

头文件定义中如下定义:
template //Type为参数类型
class TwoNum{ //由2个Type类型的数据成员构成的模板
Type a;
Type b;
public:
TwoNum(Type aa=0,Type bb=0);/ /construct function
int compate(); //element function
...
}
.cpp如下实现:
template
TwoNum::TwoNum(Type aa,Type bb):a(aa),b(bb){}

template
int TwoNum::compate(){ //比较a和b的大小
if(a>b) return 1;
else if(a==b) return 0;
else return -1;
}
...
以上代码经vc6.0验证,运行良好。