Giả sử chúng ta muốn tạo một lớp có thể cộng hai số nguyên, hai số thực và hai chuỗi (nối chuỗi). Đầu vào: số n thao tác. Mỗi thao tác: kiểu [int, float, string] và hai toán hạng. Thực hiện và hiển thị kết quả.
Ví dụ: 5 thao tác → 12 15 14.88 helloworld loveC++
Giải thuật
- Định nghĩa template class AddItems
với hàm add() và concatenate() - Main: đọc n, lặp n lần:
- Đọc type
- Nếu "float": đọc e1, e2, tạo AddItems
, gọi add(e2) - Nếu "int": đọc e1, e2, tạo AddItems
, gọi add(e2) - Nếu "string": đọc e1, e2, tạo AddItems
, gọi concatenate(e2)
Ví dụ minh họa
#include <iostream>
using namespace std;
template <class T>
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<n;i++) {
string type;
cin >> type;
if(type=="float") {
float e1,e2;
cin >> e1 >> e2;
AddItems<float> myfloat (e1);
cout << myfloat.add(e2) << endl;
}
else if(type == "int") {
int e1, e2;
cin >> e1 >> e2;
AddItems<int> myint (e1);
cout << myint.add(e2) << endl;
}
else if(type == "string") {
string e1, e2;
cin >> e1 >> e2;
AddItems<string> mystring (e1);
cout << mystring.concatenate(e2) << endl;
}
}
}
Đầu vào
5 int 5 7 int 6 9 float 5.25 9.63 string hello world string love C++
Đầu ra
12 15 14.88 helloworld loveC++