【询问】 关于调用模板类中的成员函数 谢谢
#include <iostream>
using namespace std;
template <class numtype> //声明为模板类,numtype为虚拟类型名。
class Compare //类模板名为Compare。
{
public :
Compare (numtype x, numtype y) : a (x), b (y) { }
numtype max (numtype , numtype ); //函数类型名暂定为numtype。
private :
numtype a, b;
};
template <class numtype>
numtype Compare <numtype> :: max (numtype x, numtype y) //参数类型名暂定为numtype。
{
return ((x > y) ? x : y);
}
int main ()
{
Compare <int> cmp1 (10, 5);
cout << cmp1.max () << "是两个字符中Ascll码值最大的字符。" << endl; //提说max后的括号中 函数调用中的参数太少 按我的思路 这改怎么改 书上就是这样写的 我这就错了
Compare <float> cmp2 (10.5, 10.78);
cout << cmp2.max () << "是两个字符中Ascll码值最大的字符。" << endl;
Compare <char> cmp3 ('A', 'a');
cout << cmp3.max () << "是两个字符中Ascll码值最大的字符。" << endl;
return 0;
}
[解决办法]
#include <iostream>
using namespace std;
template <class numtype> //声明为模板类,numtype为虚拟类型名。
class Compare //类模板名为Compare。
{
public :
Compare(){} //构造函数重载,这样子就能解决你这个当前的问题
Compare (numtype x, numtype y) : a (x), b (y) { }
numtype max (numtype , numtype ); //函数类型名暂定为numtype。
numtype max (){} // 这个函数重载可以解决你最初的问题了
// 但是这个无参的max函数在执行的时候,最好判断里面的a和b是否存在
private :
numtype a, b;
};
template <class numtype>
numtype Compare <numtype> :: max (numtype x, numtype y) //参数类型名暂定为numtype。
{
return ((x > y) ? x : y);
}
int main ()
{
Compare <int> cmp1;
cout << cmp1.max (10, 5) << "是两个字符中Ascll码值最大的字符。" << endl;
Compare <float> cmp2 ;
cout << cmp2.max (10.5, 10.78) << "是两个字符中Ascll码值最大的字符。" << endl;
Compare <char> cmp3 ;
cout << cmp3.max ('A', 'a') << "是两个字符中Ascll码值最大的字符。" << endl;
return 0;
}