2014-09-02 82 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