C++中的运算符重载

来源:互联网 发布:vue.js 手风琴菜单 编辑:程序博客网 时间:2024/05/22 08:07

C++中的重载运算符
运算符重载的本质就是函数重载
1.1 语法格式:

返回类型 operator 运算符名称(形参表列){        重载实体;}

例如:

const Complex operator+(const Complex &c1,const Complex &c2);//operator+重载了运算符+。

1.1.1 友元、成员函数重载

#include <iostream>using namespace std;class Complex{public:Complex(float x=0, float y=0)    :_x(x),_y(y){}void dis(){    cout<<"("<<_x<<","<<_y<<")"<<endl;}    friend const Complex operator+(const Complex &c1,const Complex &c2);    const Complex operator+(const Complex &another);    private:    float _x;    float _y;};    const Complex operator+(const Complex &c1,const Complex &c2){    cout<<"友元函数重载"<<endl;    return Complex(c1._x + c2._x,c1._y + c2._y);}const Complex Complex::operator+(const Complex & another){    cout<<"成员函数重载"<<endl;    return Complex(this->_x + another._x,this->_y + another._y);}int main(){    Complex c1(2,3);    Complex c2(3,4);    c1.dis();    c2.dis();// Complex c3 = c1+c2;// Complex c3 = operator+(c1,c2);    Complex c3 = c1+c2; //优先调用成员函数重载??    c3.dis();    return 0;}

运行结果:

(2,3)(3,4)成员函数重载(5,7)

1.1.2 双目运算符的重载

形式L#R全局函数operaror#(L,R);成员函数L.operator#(R);

例如:

#include <iostream>using namespace std;class Complex{public:Complex(float x=0, float y=0)    :_x(x),_y(y){}void dis(){    cout<<"("<<_x<<","<<_y<<")"<<endl;}Complex & operator+=(const Complex &c){    this->_x += c._x;    this->_y += c._y;    return * this;}private:    float _x;    float _y;};int main(){// int a = 10, b = 20,c = 30;// a += b;// b += c;// cout<<"a = "<<a<<endl;// cout<<"b = "<<b<<endl;// cout<<"c = "<<c<<endl;// Complex a1(10,0),b1(20,0), c1(30,0);// //(1)此时的+=重载函数返回 void// a1 += b1;// b1 += c1;// a1.dis();// b1.dis();// c1.dis();//----------------------------------------------------// int a = 10, b = 20,c = 30;// a += b += c;// cout<<"a = "<<a<<endl;// cout<<"b = "<<b<<endl;// cout<<"c = "<<c<<endl;// Complex a1(10,0),b1(20,0), c1(30,0);// //(2)此时重载函数+=返回的是 Complex// a1 += b1 += c1;// a1.dis();// b1.dis();// c1.dis();//----------------------------------------------------    int a = 10, b = 20,c = 30;    (a += b) += c;    cout<<"a = "<<a<<endl;    cout<<"b = "<<b<<endl;    cout<<"c = "<<c<<endl;    Complex a1(10,0),b1(20,0), c1(30,0);////(3)此时重载函数+=返回的是 Complex &// 一定要注意在连等式中,返回引用和返回对象的区别    (a1 += b1) += c1;    a1.dis();    b1.dis();    c1.dis();    return 0;}

1.1.3 不能重载的运算符只有四个:

. (成员运算符)::(域解析运算符)?:(条件运算符)sizeof(类型大小运算符)
原创粉丝点击