Loading... ## 重载运算符的一般格式: ```cpp 函数类型 operator 运算符名称(形参表) {对运算符的重载操作} ``` ## 不能重载的5个运算符: <div class="tip inlineBlock success"> | **.** | **成员访问运算符** | | ------------ | ------------------------ | | * | **成员指针访问运算符** | | **sizeof** | **长度运算符** | | **?:** | **条件运算符** | | **::** | **域运算符** | </div> ## 重载运算符不具备的特征: * 重载不能改变运算符对象的个数 * 重载不能改变运算符的优先级 * 重载不能改变运算符的结合性 * 重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个是类对象 * 用于类对象的运算符一般必须重载,但有两个例外,运算符”=“和”&“不必重载 ## 示例: ```cpp #include<iostream> using namespace std; class Complex{ public: int x; int y; public: Complex(int xx, int yy):x(xx), y(yy) {}; Complex(){}; // 加号运算符重载 friend Complex operator +(Complex &c1, Complex &c2); // 输出运算符重载 friend ostream & operator <<(ostream &output, Complex &c); // 输入运算符重载 friend istream & operator >>(istream &input, Complex &c1); // 减号运算符重载 friend Complex operator -(Complex &c1, Complex &c2); //大于运算符重载 friend bool operator >(Complex &c1, Complex &c2); // 小于运算符重载 friend bool operator <(Complex &c1, Complex &c2); }; Complex operator +(Complex &c1, Complex &c2){ Complex tmp = Complex(c1.x + c2.x, c1.y + c2.y); return tmp; } Complex operator -(Complex &c1, Complex &c2){ Complex tmp = Complex(c1.x - c2.x, c1.y- c2.y); return tmp; } ostream & operator <<(ostream &output, Complex &c){ cout << "圆心的坐标为:"; output << c.x << " " << c.y << endl; return output; } istream & operator >>(istream &input, Complex &c){ cout << "请输入圆心坐标:"; input >> c.x >> c.y; } bool operator >(Complex& c1, Complex& c2){ if(c1.x > c2.x){ return true; }else if(c1.y == c2.y){ if(c1.y > c2.y){ return true; }else{ return false; } }else{ return false; } } bool operator <(Complex& c1, Complex& c2){ if(c1.x < c2.x){ return true; }else if(c1.y == c2.y){ if(c1.y < c2.y){ return true; }else{ return false; } }else{ return false; } } int main() { Complex c1 = Complex(1, 2); Complex c2 = Complex(2, 2); Complex c3 = c1 + c2; if(c1 > c2) cout << "c1 > c2" << endl; else cout << "c2 > c1" << endl; Complex c = Complex(); cin >> c; cout << c; return 0; } ``` . 最后修改:2022 年 06 月 28 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果文章有用,请随意打赏。