C++ 的 运算符重载
等级 5267 次按键
为 Vector2D 重载 operator+,使两个向量可以用 a + b 相加。输出结果 (4, 6)。
C++ 代码
// 二维向量类1class Vector2D {2public: // 公有的 x、y 分量3 double x, y; // 初始化列表中的 x(x) 用参数 x 初始化成员 x4 Vector2D(double x, double y) : x(x), y(y) {}5 // 重载 +:以 const 引用接收另一个向量,且不修改 *this6 Vector2D operator+(const Vector2D& v) const { // 返回各分量相加后的新向量7 return Vector2D(x + v.x, y + v.y);8 }9};10 // 两个向量 (1, 2) 和 (3, 4)11Vector2D a(1, 2), b(3, 4);// a + b 会调用 a.operator+(b)12Vector2D c = a + b;// 输出 (4, 6)13cout << "(" << c.x << ", " << c.y << ")" << endl;运行结果
(4, 6)
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 12,× 8(× 8)× 8;× 6"× 6.× 4+× 4{× 3}× 3