c++中运算符重载允许为类类型定义算术运算行为,示例中Complex类通过成员函数重载+、-、*、/实现复数计算,遵循不改变优先级、使用const引用参数等规则,并通过友元函数重载
在C++中,运算符重载允许我们为自定义类型(如类或结构体)赋予标准运算符新的行为。算术运算符如 +、–、*、/ 等是最常被重载的运算符之一,用于实现对象之间的数学运算。
运算符重载基本规则
重载算术运算符需遵循以下规则:
- 不能改变运算符的优先级和结合性
- 不能创建新的运算符,只能重载已有运算符
- 部分运算符必须作为类的成员函数重载(如赋值 =、下标 []、函数调用 ()、成员访问 ->)
- 算术运算符通常以成员函数或友元函数形式实现,推荐使用成员函数实现 +=, -= 等复合赋值运算符,而 +, – 等可使用友元或非成员函数基于复合赋值实现
算术运算符重载示例:复数类
以下是一个简单的复数类 Complex,演示如何重载 +、-、*、/ 运算符。
立即学习“C++免费学习笔记(深入)”;
#include <iostream> using namespace std; <p>class Complex { private: double real; double imag;</p><p>public: // 构造函数 Complex(double r = 0, double i = 0) : real(r), imag(i) {}</p><pre class='brush:php;toolbar:false;'>// 显示复数 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 + 2i <pre class='brush:php;toolbar:false;'>Complex 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),建议使用非成员友元函数
- 除法等可能出错的操作应加入必要检查
基本上就这些。掌握这些模式后,可以扩展到向量、矩阵、分数等类型的运算符重载。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END