C++中运算符重载允许为类类型定义算术运算行为,示例中Complex类通过成员函数重载+、-、*、/实现复数计算,遵循不改变优先级、使用const引用参数等规则,并通过友元函数重载

在C++中,运算符重载允许我们为自定义类型(如类或结构体)赋予标准运算符新的行为。算术运算符如 +、–、*、/ 等是最常被重载的运算符之一,用于实现对象之间的数学运算。
运算符重载基本规则
重载算术运算符需遵循以下规则:
不能改变运算符的优先级和结合性不能创建新的运算符,只能重载已有运算符部分运算符必须作为类的成员函数重载(如赋值 =、下标 []、函数调用 ()、成员访问 ->)算术运算符通常以成员函数或友元函数形式实现,推荐使用成员函数实现 +=, -= 等复合赋值运算符,而 +, – 等可使用友元或非成员函数基于复合赋值实现
算术运算符重载示例:复数类
以下是一个简单的复数类 Complex,演示如何重载 +、-、*、/ 运算符。
立即学习“C++免费学习笔记(深入)”;
#include using namespace std;class Complex {private:double real;double imag;
public:// 构造函数Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 显示复数void display() const { cout << "(" << real << " + " << 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);}// 重载乘法运算符Complex operator*(const Complex& other) const { // (a+bi)(c+di) = (ac-bd) + (ad+bc)i double r = real * other.real - imag * other.imag; double i = real * other.imag + imag * other.real; return Complex(r, i);}// 重载除法运算符Complex operator/(const Complex& other) const { double denominator = other.real * other.real + other.imag * other.imag; if (denominator == 0) { cerr << "除零错误!n"; return Complex(); } double r = (real * other.real + imag * other.imag) / denominator; double i = (imag * other.real - real * other.imag) / denominator; return Complex(r, i);}// 友元函数重载输出运算符friend ostream& operator<<(ostream& os, const Complex& c) { os << "(" << c.real << " + " << c.imag << "i)"; return os;}
};
使用示例
测试上面定义的运算符重载功能:
int main() { Complex c1(3, 4); // 3 + 4i Complex c2(1, 2); // 1 + 2iComplex sum = c1 + c2;Complex diff = c1 - c2;Complex prod = c1 * c2;Complex quot = c1 / c2;cout << "c1 = "; c1.display(); cout << endl;cout << "c2 = "; c2.display(); cout << endl;cout << "c1 + c2 = "; sum.display(); cout << endl;cout << "c1 - c2 = "; diff.display(); cout << endl;cout << "c1 * c2 = "; prod.display(); cout << endl;cout << "c1 / c2 = "; quot.display(); cout << endl;// 使用友元输出cout << "使用重载<<: " << c1 << endl;return 0;
}
关键点说明
几点需要注意:
算术运算符重载通常返回一个新的对象,而不是引用,因为结果是临时值参数使用 const 引用避免拷贝,提高效率成员函数形式的重载只有一个显式参数(右侧操作数),左侧是 *this对于对称操作(如 a + b),若希望支持隐式类型转换(如 int + Complex),建议使用非成员友元函数除法等可能出错的操作应加入必要检查
基本上就这些。掌握这些模式后,可以扩展到向量、矩阵、分数等类型的运算符重载。
以上就是C++运算符重载规则 算术运算符重载示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1472419.html
微信扫一扫
支付宝扫一扫