例子

书上的原始代码:

#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 << "\n";
    // => (4,2)
    return 0;
}

相关文章:

  • 2021-11-05
  • 2022-03-03
  • 2021-05-21
  • 2021-05-28
  • 2021-07-08
  • 2021-12-25
  • 2021-07-15
猜你喜欢
  • 2022-01-08
  • 2021-11-05
  • 2021-04-14
  • 2021-11-30
  • 2022-12-23
  • 2021-10-16
相关资源
相似解决方案