2014-09-02 77 views
-1
//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;

行的地方,爲什麼會導致問題?我希望能夠真誠地獲得幫助,謝謝!

我窮英文很抱歉!

回答

4

收件函數定義爲

template<class T> 
T Pair<T>::getMax(){ 
    T max; 
    max = (value1 > value2 ? value1 : value2); 
    return max; 
} 

而且不使用可變最大。你可以簡單地寫

template<class T> 
T Pair<T>::getMax(){ 
    return value1 > value2 ? value1 : value2; 
} 

通常,如果兩個值相等,則選擇第一個值作爲最大值。所以我會寫如

template<class T> 
T Pair<T>::getMax(){ 
    return value1 < value2 ? value2 : value1; 
} 

而且一個類不能推導出它的模板參數。所以,你需要寫

Pair<int> my(100,200); 
+1

爲什麼不只是'return value1> value2? value1:value2'? – 2014-09-02 08:53:47

+0

@Wojtek Surowka我可以回答爲什麼不使用std :: max?:) – 2014-09-02 08:54:36

+0

@VladfromMoscow假設OP在創建這個代碼作爲一個學習練習,「use std :: max'」在這裏沒有幫助,但「你可以跳過'max'變量「仍然教他們一些東西。 – Angew 2014-09-02 08:59:15

2

Pair是一個模板,不是一個類型,所以你需要一個類型,你必須這樣指定它:

template<class T> 
T Pair<T>::getMax() 
     ^^^ 

,因此:

Pair<int> my(100,100); 
+0

非常感謝 – Edward 2014-09-02 08:59:48