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

在C++中,运算符重载是一种允许我们为自定义类型(如类)赋予标准运算符新含义的机制。通过它,我们可以像使用基本数据类型一样自然地操作对象,比如让两个对象相加、比较或输入输出。下面以实现一个简单的复数类为例,演示如何重载加减乘除以及输入输出流运算符。
1. 重载加减乘除运算符
假设我们要设计一个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++免费学习笔记(深入)”;
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~