带有多个参数的c++模板
C++ Templates with multiple parameters
我最近开始使用宏和模板。我用模板做了一个应用程序,你输入两个不同数据类型的整数,它会告诉你哪个更大。但每次我执行代码时它都会给我这个错误
错误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…)。
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 没有用于初始化C++中的变量模板的匹配构造函数