c++中模板与重载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33614902/article/details/84305681
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template<typename T>
T sum(T *begin, T *end){
	T *p = begin();
	T ans = 0;
	for(T *p;p!=end;p++)
		ans = ans + *p;
	return ans;
}

template<typename T>
struct Point{
	T x,y;
	Point(T x=0, T y=0){this->x = x; this->y = y;}
};

template<typename T>
Point<T> operator + (const Point<T> &a, const Point<T> &b){
	return Point<T>(a.x+b.x, a.y+b.y);
}

template<typename T>
bool operator<(const Point<T> &a, const Point<T> &b){
	if(a.x<b.x || (a.x==b.x && a.y<b.y))
		return true;
	return false;
}

template<typename T>
ostream& operator << (ostream &out, const Point<T> &a){
	out<<"("<<a.x<<","<<a.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<<endl;
	cout<<"hello,world"<<endl;
	return 0;
}

/*
C:\Users\kepcum\Desktop>g++ test.cpp -o test.exe

C:\Users\kepcum\Desktop>test.exe
(4,6)  (4.4,6.6)
hello,world
*/

猜你喜欢

转载自blog.csdn.net/qq_33614902/article/details/84305681