1 加号运算符重载
通过成员函数重载+号
通过全局函数重载+
//加号运算符重载
class Person
{
public:
//成员函数本质 p3 = p.operator+(p2);
Person operator+(Person& p1)
{
Person temp;
temp.m_A = this->m_A + p2.m_A;
temp.m_B = this->.m_B + p2.m_B;
return temp;
}
public:
int m_A;
int m_B;
};
Person operator+(Person& p1, Person& p2)
{
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
void test01()
{
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 20;
p2.m_B = 20;
Person p3 = p1 + p2;
cout << " p3.m_A =" << p3.m_A << endl;
cout << " p3.m_B = " << p3.m_B << endl;
}
总结:对于内置数据类型的表达式的运算符是不可以改变的;
不要滥用运算符重载;
2 左移运算符重载
class Person
{
friend ostream& operator<<(ostream& cout, Person& p);
public:
Person(int a, int b)
{
m_A = a;
m_B = b;
}
private:
//不会利用成员函数重载,因为无法实现cout在左侧
int m_A;
int m_B;
};
ostream & operator<<(ostream &cout,Person &p)
{
cout << "m_A = " << p.m_A << "m_B = " << p.m_B;
return cout;
}
3 递增运算发重载++
通过重载运算符,实现自己的整型数据