使用类模板添加不同项的 C++ 程序
假设我们要制作一个可以将两个整数、两个浮点数和两个字符串相加的类(字符串相加基本上是连接字符串)。作为输入,我们首先取一个数字n表示有n个不同的操作。在每个操作中,第一项是类型[int,float,string],第二项和第三项是两个操作数。所以每行将包含三个元素。我们必须阅读它们并执行上述操作。
所以,如果输入是这样的
5 int 5 7 int 6 9 float 5.25 9.63 string hello world string love C++
那么输出将是
12 15 14.88 helloworld loveC++
示例
让我们看看以下实现以获得更好的理解-
#includeusing namespace std; template class AddItems { T element; public: AddItems (T arg) { element=arg; } T add (T e2) { return element+e2; } T concatenate (T e2) { return element+e2; } }; int main(){ int n,i; cin >> n; for(i=0;i > type; if(type=="float") { float e1,e2; cin >> e1 >> e2; AddItems myfloat (e1); cout << myfloat.add(e2) << endl; } else if(type == "int") { int e1, e2; cin >> e1 >> e2; AddItems myint (e1); cout << myint.add(e2) << endl; } else if(type == "string") { string e1, e2; cin >> e1 >> e2; AddItems mystring (e1); cout << mystring.concatenate(e2) << endl; } } }
输入
5 int 5 7 int 6 9 float 5.25 9.63 string hello world string love C++输出结果
12 15 14.88 helloworld loveC++