模板与重载运算符

c++的模板和重载运算符可以大大减少代码量,而且速度较快。实例:

#include
#include
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<<"("<
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[10]={1,2,3,4,5,5,6,7,8,9};
	point b[]={point(0,1),point(2,3),point(3,4)};
	cout<
一个c++小测试,也可以试着把point也变成int和double通用的模板

尝试:

#include
#include
using namespace std;
template
struct point{
	T x,y;
	point(T x=0,T 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<<"("<
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()
{
	point a(1,2),b(2,3);
	point c(2.333,6.666);
	cout<
然后发现报错了2333,原来是定义过模板的point使用不能像原来那么随意了

#include
#include
using namespace std;
template
struct point{
	T x,y;
	point(T x=0,T y=0):x(x),y(y){}
};
template
point operator +(const point &a,const point &b)
{
	return point(a.x+b.x,a.y+b.y);
}
template
ostream& operator << (ostream &out,const point&p)
{
	out<<"("<
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()
{
	point a(1,2),b(2,3);
	point c(2.333,6.666),d(1.23,2.22);
	cout<
注释那个地方是运行不了的,模板的特性可以说是同类无敌,跨类较难吧,比如int型和double型,脑洞大了倒是补了一下

#include
#include
using namespace std;
template
struct point{
	T x,y;
	point(T x=0,T y=0):x(x),y(y){}
};
template
point operator +(const point &a,const point &b)
{
	return point(a.x+b.x,a.y+b.y);
}
template
ostream& operator << (ostream &out,const point&p)
{
	out<<"("<
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()
{
	point a(1,2),b(2,3);
	point c(2.333,6.666),d(1.23,2.22);
	cout<

这回倒是可以正常求解了,可是这是人为的2333.。。

你可能感兴趣的:(c++)