运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型;
加号运算符重载
- 作用:实现两个自定义数据类型相加的运算;
- 这时需要定义成员函数重载+号或全局函数重载+号:
定义成员函数重载+号
注意:函数中要临时创建一个对象,用来存储操作过后的数据,然后再通过重载函数进行返回对象;
class Person
{
public:
1.成员函数重载+号
Person operator+(Person &p) {
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
Person() {};
int m_A;
int m_B;
};
int main() {
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 10;
p2.m_B = 10;
Person p3 = p1 + p2;
cout << p3.m_A << " " << p3.m_B << endl;
system("pause"); //暂停一下以便查看
return 0; //标准的返回退出
}
全局函数重载+号
Person operator+(Person &p1,Person &p2) {
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p2.m_B + p2.m_B;
return temp;
}
成员函数重载本质调用:
Person p3 = p1.operator+(p2);
全局函数重载本质调用:
Person p3 = operator+(p1,p2);
以上两种可以简化为Person p3 = p1 + p2;
运算符重载,也可以发生函数重载
Person operator+(Person &p1,Person &p2) {
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p2.m_B + p2.m_B;
return temp;
}
Person operator+(Person &p1,int num) {
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
Person p3 = p1 + p2; //Person + Person
cout << p3.m_A << " " << p3.m_B << endl;
运算符重载,也可以发生函数重载
Person p4 = p1 + 100; //Person + int
cout << p4.m_A << " " << p4.m_B << endl;
左移运算符重载:
- 作用:可以输出自定义数据类型;
class Person
{
friend ostream & operator<<(ostream &cout, Person &p);
public:
Person(int a ,int b) {
this->m_A = a;
this->m_B = b;
};
private:
int m_A;
int m_B;
};
//只能利用全局函数重载左移运算符
//本质 operator<<(cout,p) 简化为 cout <<
ostream & operator<<(ostream &cout, Person &p) {
cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
return cout;
}
int main() {
Person p1(10,10);
Person p2(20,20);
cout << p1<<endl; //一般情况下如果不进行左移运算符重载,则会报错;
system("pause"); //暂停一下以便查看
return 0; //标准的返回退出
}
注意事项:
1.因为要让cout在左边,p对象在右边,所以只能通过全局函数重载左移运算符;
2. cout对象属于 Ostream类型对象 ,因为Ostream对象只有一个;所以在进行传参和返回Ostream类型数据时,只能使用引用类型;
查看某对象的数据类型——方法:按住ctrl+鼠标单击对象,再鼠标右键点击转到定义即可查看;
3.cout<<p1<<endl;中 cout 要满足链式编程,所以左移重载运算符必须返回 cout ,并且必须是Ostream&——即Ostream引用类型;这样才能让cout<<p===cout让其继续进行链式编程;
4.因为输出对象属性一般都需要访问对象的私有属性,所以,重载左移运算符一般配合友元实现自定义数据类型;
递增运算符重载
作用:通过重载递增运算符,实现自己的整型数据;
重置前置运算符
注意:是返回Myint类型的引用;——这样才能一直对一个数据进行操作
如果单纯返回Myint类型的数据,则会返回一个新数据;那么就是一直在给原数据进行操作
Myint& operator++() {
//先进行++运算
this->m_A++;
//在将自身做返回
return *this;
}
重置后置运算符
//Myint operator++(int) int代表占位参数,可以用于区分前置和后置递增
Myint operator++(int) {
//先 记录当时结果
Myint temp = *this;
//后递增
this->m_A++;
//最后将记录结果做返回
return temp;
}
Myint t1(10);
Myint t2(20);
//++(++t1);
cout << ++t1 << endl;
cout << t1<<endl;
cout << t2++ << endl;
cout << t2 << endl;
注意:
1.前置运算符返回引用——这样才能一直对一个数据进行操作
如果单纯返回Myint类型的数据,则会返回一个新数据;那么就是一直在给原数据进行操作
2.后置运算符放回值,即重新复制一个对象(返回的是一个原数据)
3.重置后置运算符Myint operator++(int) int代表占位参数,可以用于区分前置和后置递增