建立一个结构体,内含构造函数
struct point { int x,y; // =0 表示默认值为0 如果没有指定参数的值 就按0处理 point(int x=0,int y=0):x(x),y(y) {} // x(x):x的值初始化为x };
关于这个函数 还有另一种写法
point(int x=0,int y=0) { this->x=x; this->y=y; }
计算结构体的和
point operator + (const point& A,const point &B) { return point(A.x+B.x,A.y+B.y); }
结构体的流输出方式,可用cout<<p 来输出一个结构体
ostream& operator << (ostream &out,const point& p) { out<<p.x<<" "<<p.y; return out; }
定义结构体时 如:point a,b(1,2);
此时分别调用了point(),和point(1,2)
给出一个完整的代码eg
#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<<endl; return 0; }