类外定义运算符重载
作用:用于对类的对象的操作,c++可以对一般数据类型 int 等 进行运算,却无法对类的两个对象进行相加,因此,需要用运算符重载函数 operator
函数 | 功能 |
---|---|
operator + | 加法 |
operator - | 减法 |
operator * | 乘法 |
operator % | 除法 |
operator < | 小于 |
··· | ··· |
例 两个对象相加 operator()+
complex operator+( complex om1,complex om2)
{
complex temp;
temp.rear=om1.rear +0m2.rear;
temp,imag=om1.imag+om2.imag;
return temp;
}
调用 :
total =com1+com2;
或
tatol = operator( com1,com2);
不可以重载的运算符:
.(成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
? : (条件运算符)
说明 :
- **运算符重载函数的参数至少有一个是类对象。
- 不允许两个参数都是c++标准类型 运算符重载可以是 普通函数 成员函数 友元函数
- 计算机 已经含有对=的重载函数 不需要重新定义**
友元函数运算符重载
语法格式
(1)类的内部
friend 函数类型 operator 运算符 (形参表)
{
···
}
(2)类中声明原型 类外定义
class{
friend 函数类型 operator 运算符(形参表);
};
函数类型 operator 运算符 (形参表)
{
···
}
单目运算符重载
单目运算符只有一个操作数,如!a,-b,&c,*p,还有最常用的++i和–i等。
重载单目运算符的方法与重载双目运算符的方法是类似的。
但由于单目运算符只有一个操作数,因此运算符重载函数只有一个参数,如果运算符重载函数作为成员函数,则还可省略此参数。
说明:
“++”和“–”运算符有两种使用方式,前置自增运算符和后置自增运算符,它们的作用是不一样的,在重载时怎样区别这二者呢?
针对“++”和“–”这一特点,C++约定,在自增(自减)运算符重载函数中,增加一个int型形参,就是后置自增(自减)运算符函数。
这里以“-”(负号,不是减号)为例:
先用成员函数重载来实现:
class Complex{
private:
float _x;
float _y;
public:
Complex(float x = 0, float y = 0):_x(x), _y(y){}
void dis(){
cout << "( " << _x << "," << _y << " )" << endl;
}
Complex operator-(){
Complex t;
t._x = -this->_x;
t._y = -this->_y;
return t;
}
};
int main()
{
int a = 10;
cout << -a << endl;
cout << -(-a) << endl;
cout << "------------------" << endl;
Complex c(1, 1);
Complex t(2, 2);
(-c).dis();
(-(-c)).dis();
return 0;
}
双目运算符重载
class integer{
public:
integer(int value=0):value(value){}
/*integer operator+(integer itg) {
//return value+=itg.value;//i=2,ii=2
return itg.value+=value;//i=0,ii=2
}*/
friend integer operator+(const integer& a,const integer& b){//为何是const类型?
return a.value+b.value;
}
friend ostream& operator<<(ostream& os,const integer& it){
return os << it.value;
}
private:
int value;
};
参考原文:https://blog.youkuaiyun.com/qq_40871196/article/details/85682751