企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一.运算符重载 1. 本质上也是函数的重载。因此可以当做函数使用。 2. 定义运算符重载函数 + `返回类型perator 运算符(形参表)` 3. 运算符重载方式 + **成员函数** 运算符第一个操作数必须为对象自身( **不可以经过类型转换得到** ),其余操作数为形参表中的参数。 + **友元或普通函数** 运算符重载函数不是成员函数。运算符所有操作数为形参表中的参数。如果需要访问类的非公有成员,应当把该函数声明为 **友元** 。如果第一个操作数为对象自身,则调用时,第一个操作数可以通过类型转换得到得到该类。 + 如果运算符第一个操作数不是对象自身,则不能重载为 **成员函数** 。 >[warning] VC++6.0 将运算符重载函数声明为友元会出现无法访问非公有成员的BUG,详情见 *面向对象程序设计.类和对象.友元* 。 ```c++ #include <iostream> using namespace std; class Complex { private: double real_; double imaginary_; public: Complex() : real_(0), imaginary_(0) {} Complex(double real) : real_(real), imaginary_(0) {} Complex(double real, double imaginary) : real_(real), imaginary_(imaginary) {} double get_real() const { return this->real_; } double get_imaginary() const { return this->imaginary_; } Complex &set_real(double new_val) { this->real_ = new_val; return *this; } Complex &set_imaginary(double new_val) { this->imaginary_ = new_val; return *this; } //类内重载示例:重载加法运算符,第一个操作数为对象自身,第二个参数为 another Complex operator+(const Complex& another) const { return Complex(this->real_ + another.real_,this->imaginary_ + another.imaginary_); } }; //类外重载示例:重载插入运算符,第一个参数为输出流,第二个参数为 c ostream& operator<<(ostream& os,const Complex& c) { return os<<'('<<c.get_real()<<','<< c.get_imaginary()<<')'; } int main() { Complex c1(5,6),c2(7,8),c3; c3=c1+c2;//调用 c1.operator+(const Complex& another) cout<<c3;//调用 ostream& operator<<(ostream& os,const Complex& c) return 0; } ``` >[test] >(12,14) ## 二.运算符重载规则 1. 只能拓充现有运算符的功能,不能定义新的运算符,也不能改变运算符的目数、结合性、优先级等其他属性。除了重载函数调用运算符外,不可在运算符重载函数中添加默认参数。需要注意的是,运算符的重载有可能会改变运算符的求值顺序。 2. 重载的运算符至少有一个操作数为类类型。防止用户修改内置类型数据的运算性质。 3. 应当保证重载运算符的功能与运算符原有的功能类似。 4. 不可重载的运算符: + `::(域)` `.(成员访问)` `.*(成员指针访问)` `?:(条件)` `sizeof()(取大小)` `typeid()(获取类型信息)` 5. 只能 **重载为成员函数** 的运算符: + `a=b(赋值)` `a(b)(函数调用)` `a[b] (下标访问)` `a-> (成员指针访问)`