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

在C++中,运算符重载是一种允许我们为自定义类型(如类)赋予标准运算符新含义的机制。通过它,我们可以像使用基本数据类型一样自然地操作对象,比如让两个对象相加、比较或输入输出。下面以实现一个简单的复数类为例,演示如何重载加减乘除以及输入输出流运算符。
假设我们要设计一个Complex类来表示复数,包含实部和虚部。为了让两个复数对象能直接使用+、-、*、/进行运算,需要重载这些运算符。
class Complex { private: double real, imag;
public: Complex(double r = 0, double i = 0) : real(r), imag(i) {}
<font color="#808080">// 重载加法</font>
Complex <strong>operator+</strong>(<font color="#0000FF">const</font> Complex& other) <font color="#0000FF">const</font> {
<font color="#0000FF">return</font> Complex(real + other.real, imag + other.imag);
}
<font color="#808080">// 重载减法</font>
Complex <strong>operator-</strong>(<font color="#0000FF">const</font> Complex& other) <font color="#0000FF">const</font> {
<font color="#0000FF">return</font> Complex(real - other.real, imag - other.imag);
}
<font color="#808080">// 重载乘法((a+bi)*(c+di) = (ac-bd)+(ad+bc)i)</font>
Complex <strong>operator*</strong>(<font color="#0000FF">const</font> Complex& other) <font color="#0000FF">const</font> {
<font color="#0000FF">return</font> Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
<font color="#808080">// 重载除法(略复杂,需考虑分母模长)</font>
Complex <strong>operator/</strong>(<font color="#0000FF">const</font> Complex& other) <font color="#0000FF">const</font> {
<font color="#0000FF">double</font> denominator = other.real * other.real + other.imag * other.imag;
<font color="#0000FF">return</font> Complex(
(real * other.real + imag * other.imag) / denominator,
(imag * other.real - real * other.imag) / denominator
);
}
<font color="#808080">// 提供访问函数</font>
<font color="#0000FF">void</font> print() <font color="#0000FF">const</font> {
std::cout << "(" << real << " + " << imag << "i)";
}};
上述代码中,所有二元运算符都作为成员函数实现,接收一个常量引用参数,返回新的Complex对象。这样可以链式调用,且不修改原对象。
立即学习“C++免费学习笔记(深入)”;
输入输出流( 和 >>)不能作为成员函数重载,因为它们的操作对象是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
基本上就这些。掌握运算符重载后,可以让自定义类型更直观易用,提升代码可读性和封装性。关键在于合理设计接口,遵循直觉,不滥用特性。
以上就是C++运算符重载教程_C++重载加减乘除与输入输出流的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号