简体   繁体   English

使用C ++模板的错误C2955和错误C2244

[英]error C2955 and error C2244 using C++ template

I'm starting learning C++ template. 我开始学习C ++模板。 Now, I'm trying to compile the simple example of C++ template. 现在,我正在尝试编译C ++模板的简单示例。

#include <iostream.h>
template <class T> class pair1 {
     T value1, value2;
public:
    pair1 (T first, T second) {
        value1=first;
        value2=second;
    }
    T getmax ();
};

template <class T> 
T pair1::getmax (){
     T retval;
    retval = value1>value2? value1 : value2;
    return retval;
}
int main(){
     pair1<int> myobject (100, 75);
    cout << myobject.getmax()<<endl;
system("pause");
return 0;
}

I occured the following 2 errors: 我发生以下2个错误:

  • (1) error C2955: 'pair1':use of template requires template argument list (1)错误C2955:'pair1':使用模板需要模板参数列表
  • (2) error C2244:'pair1::getmax':unable to match function definition to an existing declaration (2)错误C2244:'pair1 :: getmax':无法使函数定义与现有声明匹配

I'm using the Visual Studio 2010. 我正在使用Visual Studio 2010。

When use inline function as following, it worked fined: 当按以下方式使用内联函数时,它被罚款:

#include <iostream.h>
template <class T> class pair1 {
     T value1, value2;
public:
    pair1 (T first, T second) {
        value1=first;
        value2=second;
    }
   **T getmax (){ T retval;
retval = value1>value2? value1 : value2;
return retval;};**
};


int main(){
     pair1<int> myobject (100, 75);
    cout << myobject.getmax()<<endl;
system("pause");
return 0;
}

However, i prefer not using inline function in this situation, hope anyone can tell what's wrong with the first block of C++ template code. 但是,我更喜欢在这种情况下不使用内联函数,希望任何人都可以说出C ++模板代码的第一部分出了什么问题。

You should use template parameter for class. 您应将模板参数用于类。

template <class T> 
T pair1<T>::getmax (){
     T retval;
    retval = value1>value2? value1 : value2;
    return retval;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM