使用類模板新增不同專案的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++

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個名為AddItems的類,使用類模板。它有兩個函式add()和concatenate()。add()將新增整數和浮點數,而concatenate()將連線字串。

  • 從主方法中執行以下操作:

  • 初始化 i := 0,當 i < n 時,更新(i 增加 1),執行:

    • type := 當前型別

    • 如果type與"float"相同,則:

      • 獲取兩個運算元e1和e2

      • 建立一個名為myfloat的AddItems物件,型別為float,專案為e1

      • 呼叫myfloat.add(e2)並顯示結果

    • 否則,如果type與"int"相同,則:

      • 獲取兩個運算元e1和e2

      • 建立一個名為myint的AddItems物件,型別為int,專案為e1

      • 呼叫myint.add(e2)並顯示結果

    • 否則,如果type與"string"相同,則:

      • 獲取兩個運算元e1和e2

      • 建立一個名為mystring的AddItems物件,型別為string,專案為e1

      • 呼叫mystring.concatenate(e2)並顯示結果

示例

讓我們看看下面的實現,以便更好地理解:

#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;
        }
    }
}

輸入

5
int 5 7
int 6 9
float 5.25 9.63
string hello world
string love C++

輸出

12
15
14.88
helloworld
loveC++

更新於:2021年10月7日

624 次瀏覽

啟動您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.