天天看點

刷野打怪上王者·C++篇·第21期·模闆處理

參考連結

​​RUNOOB.COM​​

模闆處理

   函數模闆不是一個實在的函數,編譯器不能為其生成可執行代碼。定義函數模闆後隻是一個對函數功能架構的描述,當它具體執行時,将根據傳遞的實際參數決定其功能。模闆分為函數模闆和類模闆。

函數模闆的定義方式

template <class type1, class type2, ...> 傳回類型 函數名(參數清單)
{
    /*核心函數*/
}      

執行個體

#include <iostream>

using namespace std;

template <typename T>
inline T const& addition(T const& var1, T const& var2) //定義模闆函數 根據資料的資料類型來确定T的類型
{
  return var1 + var2;
}

int main()
{
  cout << "2 + 3 = " << addition(2, 3) << endl;
  cout << "2.5 + 3.5 = " << addition(2.5, 3.5) << endl;

  getchar();
}      

運作結果

2 + 3 = 5
2.5 + 3.5 = 6      

類模闆的定義方式

template <class type> class 類名
{
    /*核心函數*/
}      

執行個體

#include <iostream>
#include <string>

using namespace std;

template <typename T>
class ComplexClass {

public:
  //構造函數
  ComplexClass(T a, T b)
  {
    this->iVar1 = a;
    this->iVar2 = b;
  }

  //運算符重載
  ComplexClass<T> operator+(ComplexClass &c)
  {
    ComplexClass<T> tmp(this->iVar1 + c.iVar1, this->iVar2 + c.iVar2);
    cout << "iVar1 = " << tmp.iVar1 << " iVar2 = " << tmp.iVar2 << endl;
    return tmp;
  }

private:
  T iVar1;
  T iVar2;
};

int main()
{
  //對象的定義,必須聲明模闆類型,因為要配置設定内容
  ComplexClass<int> complex1(10, 20);
  ComplexClass<int> complex2(20, 30);
  ComplexClass<int> complex3 = complex1 + complex2;
  getchar();
  return 0;
}      

運作結果

iVar1 = 30 iVar2 = 50      

更多《計算機視覺與圖形學》知識,可關注下方公衆号: