【发布时间】:2014-04-21 22:29:18
【问题描述】:
我最近开始使用宏和模板。我使用模板制作了一个应用程序,您可以在其中输入两个具有不同数据类型的整数,它会告诉您哪个更大。但是每次我执行代码它都会给我这个错误
错误 1 错误 C2371:'comp':重新定义;不同的基本类型 行:36 列:1
这是我的代码
#include <iostream>
using namespace std;
template<typename T, typename B>
class Compare{
public:
Compare(const T& hAge1, const B& hAge2){
age1 = hAge1;
age2 = hAge2;
}
void display_result(){
if (age1 > age2){
cout << "Your age is bigger" << endl;
}
else{
cout << "Your age is smaller" << endl;
}
}
private:
T age1;
B age2;
};
int main(){
int your_age;
int someother_age;
//user interface
cout << "Enter your age: ";
cin >> your_age;
cout << "Enter some other age: ";
cin >> someother_age;
/*create instance of class Comepare*/
Compare<int,double>comp(your_age, someother_age);
comp.display_result();
//create another instance
Compare<int, int>comp(your_age, someother_age);
comp.display_result();
system("pause");
return 0;
}
【问题讨论】:
-
您的示例可以简化为
int main() {int a; double a;}或类似的。这是同样的问题,这是编译时错误,而不是运行时错误。 -
您的编译器会准确地告诉您问题所在。它甚至会告诉您在哪一行和哪个符号被重新定义。为了更容易,第一个定义只是上面几行。 再简单不过了。
标签: c++ class templates compiler-errors