0
点赞
收藏
分享

微信扫一扫

C++ 核心 4.5 运算符重载

4.5 运算符重载

对已有的运算符重新定义,赋予其另一种功能以适应不同的数据类型。

4.5.1 加号运算符重载

operator+ 通过成员函数重载

Person operator+(Person &p){
    Persom temp;
    temp.A = this->A + p.A;
    temp.B = this->B + p.B;
    return temp;
}

通过全局函数重载

Person operator+(Person &p1, Person &p2){
    Persom temp;
    temp.A = p1.A + p2.A;
    temp.B = p1.B + p2.B;
    return temp;
}

然后可以使用:

Person p3 = p1 + p2 ; //调用重载的operator+

4.5.2 <<左移运算符重载

输出对象。 通过全局函数重载:

ostream & operator<<(ostream& out, Person &p) {
    out<<p.A<<" "<<p.B;
}

又因为我们一般将属性设置为私有,所以为了让这个全局函数能访问私有属性,还要将它设置为友元。

4.5.3 递增运算符重载

MyInteger& operator++()

后++,用int做占位参数,区分前++和后++。 MyInteger operator++(int)

MyInteger operator++(int){
    MyInteger temp = *this;
    n_Num ++;
    return temp;
}

将++改为--就是自减运算符。

4.5.4 赋值运算符重载

Person& operator=(Person &p)

解决浅拷贝问题。自己在赋值运算符中使用深拷贝(申请内存)

4.5.5 关系运算符重载

bool operator==(Person &p) bool operator!=(Person &p)

4.5.6 函数调用运算符重载

括号重载 operator() 也称仿函数。 写法灵活。

class MyPrint{
public:
    //重载()
    void operator()(string test){
        cout << test << endl; 
    }

};
...
MyPrint mprint;
mprint("hello"); //使用类似函数调用,因此称为仿函数
举报

相关推荐

C++运算符重载

C++ 运算符重载

C++——运算符重载

C++(运算符重载)

【c++运算符重载】

【C++】运算符重载

0 条评论