C++类和对象--运算符重载

要须心地收汗马,孔孟行世目杲杲。这篇文章主要讲述C++类和对象--运算符重载相关的知识,希望能为你提供帮助。
运算符重载
对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
运算符重载也可以发生函数重载
对于内置的数据类型的表达式的运算符是不可能改变的
不要滥用运算符重载
加号运算符重载
作用:实现两个自定义数据类型相加的运算
成员函数重载

#include < iostream>
using namespace std;
class Person
{
public:
//成员函数重载 +
Person operator+(Person& p)
{
Person temp;
temp.A = this-> A + p.A;
temp.B = this-> B + p.B;
return temp;
}
int A;
int B;
};
void test1()
{
Person p1;
p1.A = 10;
p1.B = 20;
Person p2;
p2.A = 30;
p2.B = 40;
Person p3;
//成员函数重载本质调用
//Person p3 = p1.operator+(p2);
p3 = p1 + p2;
cout < < "p3.A = " < < p3.A < < endl;
cout < < "p3.B = " < < p3.B < < endl;

}
int main()
{
test1();
}

全局函数重载
#include < iostream>
using namespace std;
class Person
{
public:
int A;
int B;
};
//全局函数重载 +
Person operator + (Person& p1, Person& p2)
{
Person temp;
temp.A = p1.A + p2.A;
temp.B = p1.B + p2.B;
return temp;
}
void test1()
{
Person p1;
p1.A = 10;
p1.B = 20;
Person p2;
p2.A = 30;
p2.B = 40;
Person p3;
//全局函数重载本质调用
//Person p3 = operator+ (p1, p2);
p3 = p1 + p2;
cout < < "p3.A = " < < p3.A < < endl;
cout < < "p3.B = " < < p3.B < < endl;

}
int main()
{
test1();
}

左移运算符重载
作用:可以输出自定义数据类型
#include < iostream>
using namespace std;
class Person
{
friend ostream& operator< < (ostream& cout, Person& p);
public:
Person(int a, int b)
{
A = a;
B = b;
}
private:
int A;
int B;
};
//只能利用全局函数重载 < <
ostream& operator< < (ostream& cout, Person & p)
{
cout < < "p1.A: " < < p.A < < endl;
cout < < "p1.B: " < < p.B < < endl;
return cout;
}
void test1()
{
Person p1(10, 20);
cout < < p1 < < endl;
}
int main()
{
test1();
}

递增运算符重载
【C++类和对象--运算符重载】作用:通过递增运算符重载,实现自己的整型数据
#include < iostream>
using namespace std;
//自定义整型
class MyInteger
{
friend ostream& operator< < (ostream& cout, MyInteger& myint);
public:
MyInteger()
{
Num = 0;
}
//重载前置++运算符
//返回引用是为了一直对一个数据进行递增操作
MyInteger& operator++()
{
Num++;
//将自身做返回
return *this;
}
//重载后置++运算符
//int代表占位参数,可以用于区分前置++和后置++
//返回值不返回引用,避免非法操作
MyInteger operator++(int)
{
//先记录结果
MyInteger temp = *this;
//后递增
Num++;
//最后返回记录的结果
return temp;
}
private:
int Num;
};
//重载左移运算符
ostream& operator< < (ostream& cout, MyInteger& myint)
{
cout < < myint.Num;
return cout;
}
void test1()
{
MyInteger myint;

    推荐阅读