带有多个参数的c++模板

C++ Templates with multiple parameters

本文关键字:c++ 模板 参数      更新时间:2023-10-16

我最近开始使用宏和模板。我用模板做了一个应用程序,你输入两个不同数据类型的整数,它会告诉你哪个更大。但每次我执行代码时它都会给我这个错误

错误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;
}

您只是在一个作用域中声明了两个具有相同名称的对象。这些是不是模板完全无关紧要。你可能想把变量和它们的使用放在一个专门的块中,例如

{
    /*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这个名字,因为它不太具有描述性(compute, compare, compatible, comp…)。