c++运算符重载

应用举例:

#include <iostream>
using namespace std;

class Coord
{
public:
    Coord(int _x=0, int _y=0)
        :x(_x), y(_y){}

//成员函数  单目运算符重载   
 Coord operator-()     
    {
        Coord c;
        c.x = -this->x;
        c.y = -this->y;
        return (c);
    }

 //友元函数  双目运算符重载   
    friend Coord operator+(Coord &k, Coord&j)
    {
        Coord i(0, 0);
        i.x = k.x + j.x;
        i.y = k.y + j.y;
        return i;
    }

    //友元函数  流运算符重载  
    friend ostream& operator<<(ostream &os, Coord &c) 
    {
        os << "[" << c.x << "," << c.y << "]";
        return os;
    }

    friend istream& operator>>(istream&is, Coord&c)
    {
        is >> c.x;
        is >> c.y;
        return is;
    }

private:
    int x;
    int y;

};


int main()
{
    Coord a, b, c;
    cin >> a >> b;
    c = a + b;
    cout << c << endl;
    cout << -c << endl;
    cout << -(-c) << endl;
    system("pause");
    return 0;
}


//VS2013编译通过   

小结:
1.不可重载的运算符
. (成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
?: (条件运算符)
2.只能重载为成员函数的运算符
= (赋值运算符)
[] (下标运算符)
() (函数运算符)
-> (间接成员访问)
->* (间接取值访问)
3.
【1】所有的单目运算符 一般用成员重载
【2】+= -= /= *= ^= &= != %= >>= <<=
一般用成员重载 (涉及到连续赋值)
【3】其他双目运算符 一般用 非成员

未完 待续>>>>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值