版权声明:本人菜鸟一只,如文章有错误或您有高见,请不吝赐教 https://blog.csdn.net/qq_41138935/article/details/83543750
代码来自 算法竞赛与入门经典第二版-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;
}