MST

星途 面试题库

面试题:C++运算符重载基础

请说明如何在C++中重载二元运算符 '+' 用于自定义类,假设我们有一个名为 `Vector2D` 的类,包含 `x` 和 `y` 两个成员变量表示二维向量的坐标,要求重载 '+' 运算符实现向量加法并返回新的 `Vector2D` 对象。
49.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
class Vector2D {
public:
    int x;
    int y;

    Vector2D(int a = 0, int b = 0) : x(a), y(b) {}

    // 重载二元运算符 '+'
    Vector2D operator+(const Vector2D& other) const {
        return Vector2D(x + other.x, y + other.y);
    }
};