//class template
#include<iostream>
using namespace std;
template <class T> class Pair{
T value1,value2;
public:
Pair(T first,T second){
value1 = first;
value2 = second;
}
T getMax();
};
template<class T>
T Pair::getMax(){
T max;
max = (value1 > value2) ? value1 : value2;
return max;
}
int main(){
Pair my(100,200);
cout << my.getMax() << endl;
return 0;
}
当我运行该程序时,问题发生:C++模板不起作用
[Error] F:\c#\cplusplus\demo_code\demo11_template2.cpp:16: error: `template<class T> class Pair' used without template parameters
其中出现该问题是在“T配对:: GetMax的(){”的线的地方;
[Error] F:\c#\cplusplus\demo_code\demo11_template2.cpp:18: error: `value1' was not declared in this scope
[Error] F:\c#\cplusplus\demo_code\demo11_template2.cpp:18: error: `value2' was not declared in this scope
哪里出现问题是在max = (value1 > value2) ? value1 : value2;
行的地方,为什么会导致问题?我希望能够真诚地获得帮助,谢谢!
我穷英文很抱歉!
为什么不只是'return value1> value2? value1:value2'? – 2014-09-02 08:53:47
@Wojtek Surowka我可以回答为什么不使用std :: max?:) – 2014-09-02 08:54:36
@VladfromMoscow假设OP在创建这个代码作为一个学习练习,“use std :: max'”在这里没有帮助,但“你可以跳过'max'变量“仍然教他们一些东西。 – Angew 2014-09-02 08:59:15