【问题标题】:C++ Templates with multiple parameters具有多个参数的 C++ 模板
【发布时间】: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


【解决方案1】:

您只是在一个范围内声明了两个具有相同名称的对象。这些是否是模板完全无关紧要。您可能希望将变量及其使用的变量放在专用块中,例如

{
    /*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();
}

当然,您也可以只用不同的方式命名您的对象,而不是重用名称 comp,这无论如何都不太具有描述性(计算、比较、兼容、比较...)。

【讨论】:

  • 当我用不同的对象(即“com”)重命名第二个比较实例时。它确实有效,但它也显示了第一个比较实例“comp”的输出和第二个“com”的输出
  • @jim 你期待什么?代码完全按照您的要求执行? 显然,在您的情况下,如果您使用整数或双精度数,答案将是相同的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2012-12-26
  • 2011-06-10
相关资源
最近更新 更多