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;
}
这里面我们定义了一个名叫Point的结构体,这里面的元素是两个整数,我们还在里面定义了一个同名的构造函数,在下面的Point a, b(1, 2);中,我们分别调用了Point()和Point(1,2),然后我们还定义了结构体Point的“+”运算,最后我们还定义了结构体Point的输出规则,这样就可以规定他在被out时候的格式了。
注释1:那个x(x), y(y)就和类里面的私有变量的传值差不多的东西。不想这么写的话还可以
Point(int x=0,int y=0){this->x=x;this->y=y;}