//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