1. 程式人生 > >C++結構體與模板

C++結構體與模板

程式碼來自 演算法競賽與入門經典第二版-p105

#include<iostream>

using namespace std;

struct Point{
	int x,y;
	Point(int x=0,int y=0):x(x),y(y){}
};

Point operator + (const Point& A,const Point& B){
	return Point(A.x+B.x,A.y+B.y);
}

ostream& operator << (ostream &out,const Point& p){
	out<<"("<<p.x<<","<<p.y<<")";
	return out;
}
int main(){
	Point a,b(1,2);
	a.x=3;
	cout<<a+b<<"\n";
	return 0;
}

結果:

模板:

以求陣列和為例,

#include<iostream>

using namespace std;


template<typename T>
T sum(T* begin,T* end){
	T *p=begin;
	T ans=0;
	for(T *p=begin;p!=end;p++)
		ans=ans+*p;	//結構體只有+運算子
	return ans; 
}

int main(){
	double a[]={1.1,2.2,3.3,4.4};
	cout<<sum(a,a+4)<<"\n";
	return 0;
}