重载+号运算符
在有些时候,比如重载加号运算符,能做一些普通的运算,却无法把两个类相加。可以重新定义+ 运算符
- 重载+运算符的功能函数就是operator关键字,后边加要重载的符号。
- 重载运算符可以重载函数,可以写多个版本的重载运算符,(类+类、类+整形、……)
- 重载运算符函数可以写在类内也可以写在类外,一般写在类内能少些一个形参。
class Persion
{
public:
int age;
//成员函数重载
Persion operator+(Persion & p);
};
Persion Persion::operator+(Persion & p)
{
Persion itemp;
itemp.age = this->age + p.age;
return itemp;
}
//或者重载函数合一写到全局函数
Persion operator+(Persion &p1, Persion &p2)
{
Persion itemp;
itemp.age = p1.age + p2.age;
return itemp;
}
Persion operator+(Persion &p1, int num)
{
Persion itemp;
itemp.age = p1.age + num;
return itemp;
}
左移运算符重载
左移运算符用在 cout << ……这种形式,只能用来输出内置数据类型,如果我们想输出自定义数据类型,就需要重载左移运算符。
(1)从上边我们知道,重载运算符可以在类内,也可以在类外。如果在类内
class Persion
{
void operator<<(cout)
//这种写法在调用的时候,简化完之后就是 this << cout ,很显然不符合我们的要求(要求就是cout 必须在左边,而成员函数的写法,cout只能写在右边)
}
cout这种运算符一定能满足链式编程,所以返回值应该是指针或者引用
class Persion
{
public:
int age;
Persion(int age)
{
this->age = age;
}
};
ostream& operator<<(ostream& cout, Persion& p)
{
cout << p.age;
return cout;
}
void text01(void)
{
Persion p1(20);
cout << p1 << endl;;
}