C++中的运算符重载

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(类型大小运算符)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值