一个FLAG #18# 再谈结构体

例子

书上的原始代码:

#include <iostream>

using namespace std;

struct Point {
    int x, y;
    Point(int x = 0, int y = 0): x(x), y(y) {
        // x(x), y(y) 等价于
        // this->x = x; this->y = y; 
    }
};

Point operator + (const Point &A, const Point &B) { // 在 struct 内部定义加法 是单个参数。 
    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); // 与 java 不同, 它不需要手动去new
    // 在这里直接自动调用了 Point() 以及 Point(1, 2) 
    a.x = 3;
    cout << a + b << "
";
    // => (4,2)
    return 0;
}
原文地址:https://www.cnblogs.com/xkxf/p/12704127.html