#include<iostream>
using namespace std;
template <typename T> //定義模板的固定格式
struct Point{
T x,y; //成員變量
Point(T x=0,T y=0):x(x),y(y){ //構造函數
}
};
template <typename T> //定義模板的固定格式
Point <T> operator + (const Point<T>&A,const Point<T>&B){ //重載operator+
return Point<T>(A.x+B.x,A.y+B.y) ;
}
template <typename T> //定義模板的固定格式
ostream& operator << (ostream &out,const Point<T>& p){ //ostream是output stream的簡稱,即輸出流;<<操作重載
out <<"("<<p.x<<","<<p.y<<")";
return out;
}
int main()
{
Point<int> a(1,2),b(3,4);
Point<double> c(1.1,2.2),d(3.3,4.4);
cout<<a+b<<" "<<c+d<<"\n";
return 0;
}
c++中 模板與重載入門代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.