【C++】学习笔记草稿版系列11(运算符重载)

运算符重载和友元之间是如何发生关系的

友元重载,成员重载
单目和双目运算符可以重载
通常情况下:
双目运算符重载为成员的话需要一个参数,重载为友元的话需要两个参数

const Complex operator+(Complex& another);
friend Complex operator+(Complex & a, Complex & b);

单目运算符重载为成员的话需要0个参数,重载为友元的话需要1个参数。
不必重载的运算符(= &)

// 运算符重载
class Complex
{
public:
    Complex(float x = 0, float y = 0)
        :_x(x), _y(y){}
    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<")"<<endl;
    }
    friend Complex operator+(Complex & a, Complex & b);
    Complex operator+(Complex & another);
private:
    float _x;
    float _y;
};

Complex operator+(Complex & a, Complex & b)
{
    Complex t;
    t._x = a._x + b._x;
    t._y = a._y + b._y;

    return t;
}
Complex Complex::operator+(Complex & another)
{
    Complex t;
    t._x = this->_x + another._x;
    t._y = this->_y + another._y;

    return t;
}


int main()
{
    Complex c1(1, 2), c2(2, 3);
    Complex c = c1 + c2;

    c1.dis()
    c2.dis()
    c.dis()
    return 0;
} 
class Complex
{
public:
    Complex(float x = 0, float y = 0)
        :_x(x), _y(y){}
    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<")"<<endl;
    }
    Complex & operator+=(const Complex & another);
    Complex operator-()
    {
        return Complex(-this->_x, -this->_y);
    }
private:
    float _x;
    float _y;
};

Complex & Complex::operator+=(const Complex & another)
{
    this->_x += another._x;
    this->_y += another._y;

    return *this;
}

流输入输出运算符重载

希望能够实现的情况

Complex c(1, 2);
cout<<c<<endl;
//cout是一个流对象,ostream类型,<<是一个双目运算符
//不能实现:cout.operator<<(x)
//可以实现:operator<<(cout, c)

类段的代码

class Complex
{
public:
    Complex(float real = 0, float image = 0)
        :_x(real), _y(image){}
    void dis()
    {
        cout<<"("<<_x<<", "<<_y<<")"<<endl;
    }
    friend ostream & operator<<(ostream & os, const Complex &c)
    {
        os<<"("<<c._x<<", "<<c._y<<")"<<endl;
        return os;
    }
    friend istream & operator<<(istream & is, Complex &c)
    {
        is>>c._x>>c._y;
        return is;
    }
private:
    float _x;
    float _y;
};

流输入输出运算符重载

istream & operator>>(istream &, 自定义类 &);
ostream & operator<<(ostream &, 自定义类 &);

不可重载的运算符

. ——成员访问运算符
.*——成员指针访问运算符
::——域运算符
sizeof——长度运算符
?:——条件运算符

注意事项

  1. 一个操作符的左右操作数不一定是相同类型的对象,这就涉及到将该操作符函数定义为谁的友元,谁的成员问题。
  2. 一个操作符函数,被声明为哪个类的成员,取决于该函数的调用对象(通常是左操作数)。
  3. 一个操作符函数,被声明为哪个类的友元,取决于该函数的参数对象(通常是右操作数)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值