运算符重载允许为类类型定义+、-、*、/等操作,如Complex类通过成员函数重载加减乘除实现复数运算,输出输入流需以友元函数重载,保持操作直观且不改变原对象,提升代码可读性与易用性。

在C++中,运算符重载是一种允许我们为自定义类型(如类)赋予标准运算符新含义的机制。通过它,我们可以像使用基本数据类型一样自然地操作对象,比如让两个对象相加、比较或输入输出。下面以实现一个简单的复数类为例,演示如何重载加减乘除以及输入输出流运算符。
1. 重载加减乘除运算符
假设我们要设计一个Complex类来表示复数,包含实部和虚部。为了让两个复数对象能直接使用+、-、*、/进行运算,需要重载这些运算符。
class Complex { private: double real, imag;
public: Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载加法
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载减法
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
// 重载乘法((a+bi)*(c+di) = (ac-bd)+(ad+bc)i)
Complex operator*(const Complex& other) const {
return Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
// 重载除法(略复杂,需考虑分母模长)
Complex operator/(const Complex& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return Complex(
(real * other.real + imag * other.imag) / denominator,
(imag * other.real - real * other.imag) / denominator
);
}
// 提供访问函数
void print() const {
std::cout << "(" << real << " + " << imag << "i)";
}};
上述代码中,所有二元运算符都作为成员函数实现,接收一个常量引用参数,返回新的Complex对象。这样可以链式调用,且不修改原对象。
立即学习“C++免费学习笔记(深入)”;
2. 重载输入输出流运算符
输入输出流( 和 >>)不能作为成员函数重载,因为它们的操作对象是std::ostream或std::istream,而不是我们的类。因此必须定义为友元函数或普通全局函数。
friend std::ostream& operator(std::ostream& out, const Complex& c) { out return out; }
friend std::istream& operator>>(std::istream& in, Complex& c) { in >> c.real >> c.imag; return in; }
将这两个函数声明为Complex类的友元,以便访问其私有成员。使用方式如下:
Complex a(3, 4), b(1, 2); Complex c = a + b; std::cout
std::cin >> a; // 输入两个数字分别赋给 real 和 imag
3. 注意事项与建议
- 保持语义一致:重载后的运算符行为应符合常规理解,比如+应该用于合并而非修改对象。
- 优先使用成员函数重载对称运算符(如+、-),但和>>必须是全局函数。
- 返回类型通常为值或引用,避免返回局部变量的引用。
- 对于复合赋值运算符(如+=),推荐作为成员函数实现,并返回*this以支持链式赋值。
基本上就这些。掌握运算符重载后,可以让自定义类型更直观易用,提升代码可读性和封装性。关键在于合理设计接口,遵循直觉,不滥用特性。









