您的位置:首页 > 编程语言 > C语言/C++

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

2018-02-19 21:25 651 查看

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

友元重载,成员重载

单目和双目运算符可以重载

通常情况下:

双目运算符重载为成员的话需要一个参数,重载为友元的话需要两个参数

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——长度运算符

?:——条件运算符

注意事项

一个操作符的左右操作数不一定是相同类型的对象,这就涉及到将该操作符函数定义为谁的友元,谁的成员问题。

一个操作符函数,被声明为哪个类的成员,取决于该函数的调用对象(通常是左操作数)。

一个操作符函数,被声明为哪个类的友元,取决于该函数的参数对象(通常是右操作数)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: