第16章 - 运算符重载
嗨,朋友!我是长安。
运算符重载让我们可以为自定义类型定义运算符的行为,就像内置类型一样使用。
➕ 基本运算符重载
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载 + 运算符
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
// 重载 << 运算符(友元函数)
friend ostream& operator<<(ostream& out, const Complex& c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex c3 = c1 + c2; // 使用重载的+运算符
cout << c3 << endl; // 使用重载的<<运算符
}
🔍 常用运算符重载
class Vector {
private:
int x, y;
public:
Vector(int a = 0, int b = 0) : x(a), y(b) {}
Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y); }
Vector operator-(const Vector& v) { return Vector(x - v.x, y - v.y); }
bool operator==(const Vector& v) { return x == v.x && y == v.y; }
friend ostream& operator<<(ostream& out, const Vector& v) {
out << "(" << v.x << ", " << v.y << ")";
return out;
}
};
➡️ 第17章 - 模板基础
