1.加号运算符重载
C++内置的数据类型是可以直接相加的
但是用户定义类型呢
也是可以的,不够这要求我们自己重载运算符
在系统内置函数中operator 运算符 ()
#include <iostream>
using namespace std;
class Person
{
public:
Person operator+(Person& p)
{
Person temp;
temp.age = this->age + p.age;
return temp;
}
public:
int age;
};
Person operator+(Person &p1,Person &p2)
{
Person temp;
temp.age= p1.age + p2.age;
return temp;
}
int main()
{
Person p1, p2;
p1.age = 10;
p2.age = 20;
Person p3 = p1.operator+(p2);
Person p4 = operator+(p1, p2);
cout << p3.age << endl;
cout << p4.age << endl;
}
p1.operator+(p2); ---》p1+p2
operator+(p1, p2); --》p1+p2
当然* / - %也能重载
不能滥用,函数定义和函数实现意义要一致
2.左移运算符重载
C++中,可以对内定基础类型输出,
int a;
cout<<a;
class Person
{
private:
int m_a;
int m_b;
}
cout<<p; 这个是不能的。
但是能通过重载左移运算符输出
首先,成员函数不能重载左移运算符
因为成员函数的调用必须先是对象 而 cout<<p;
cout在运算符的左边,显然是不行的
可以通过全局函数重载
#include <iostream>
using namespace std;
class Person
{
public:
Person (int a,int b)
{
m_age=a;
m_num=b;
}
public:
int m_age;
int m_num;
};
ostream& operator<<(ostream & cout, Person& p)//引用传入,引用返回,因为链式调用,返回值要为cout对象本身
{
cout << p.m_age << " " << p.m_num << endl;
return cout;
}
int main()
{
Person p1(10, 20);//要输出10,20两个数据
cout << p1 << endl;
}
同理,>>运算符也可以
3.递增运算符重载
这个我有点懵,前置++和后置++方式不同
#include <iostream>
using namespace std;
//++运算符重载
class Myint
{
public:
Myint()
{
num = 0;
}
Myint& operator++()//前置运算符要返回引用,因为前置运算符满足链式
{
num++;
return *this;
}
Myint operator++(int) //后置返回的是自增前的值
{
Myint temp = *this;
num++;
return temp; //返回值,不能返回局部变量的引用
}
public:
int num;
};
ostream& operator<<(ostream &cout,Myint &myint)
{
cout << myint.num << endl;
return cout;
}
int main()
{
Myint myint;
cout <<++myint << endl;
}
后置++重载可能会报错