2021.11.23
类和对象之运算符重载
1.加法运算符重载
class Person
{
public:
Person() {}; //默认构造函数,用于后面定义Person temp;
Person(int a, int b)
{
m_A = a;
m_B = b;
}
//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;
//}
int m_A, 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;
}
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 p1(10, 10);
Person p2(10, 10);
成员函数重载本质为:Person p3 = p1.operator+(p2);
全局函数重载本质为:Person p3 = operator+(p1,p2);
Person p3 = p1 + p2;
Person p4 = p1 + 100;
2.左移运算符重载
ostream& operator<<(ostream &out, Person &p) //类代码与上述代码相似
{
out << "m_A= " << p.m_A << "\tm_B=" << p.m_B;
return out;
}
//调用
cout << p << endl;
3.递增运算符重载
class MyInit {
friend ostream& operator<<(ostream& out, MyInit myinit);
public:
MyInit() {
m_Num = 0;
}
MyInit& operator++() //前置运算符,++a,先加后赋值
{
m_Num++;
return *this;
}
MyInit operator++(int) //后置运算符,a++,先赋值再++
{ //这里用占位参数,让编译器知道作后置递增
MyInit temp;
temp = *this;
m_Num++;
return temp;
}
private:
int m_Num;
};
//调用
MyInit myinit;
cout << ++(++myinit) << endl;
cout << myinit++ << endl;
这里进行cout输出需要用到上一部分的左移重载
4.赋值运算符重载
class Person{
public:
Person(int age) {
m_Age = new int(age);
}
~Person() {
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
Person& operator=(Person& p) {
if (m_Age != NULL) //先判断是否有属性在堆区,如果有先释放,然后再进行深拷贝
{
delete m_Age;
m_Age = NULL;
}
m_Age = new int(*p.m_Age);
return *this;
}
int *m_Age;
};
//调用
Person p1(18);
Person p2(20);
Person p3(25);
p3 = p2 = p1;
5.关系运算符重载
class Person {
public:
Person(string name, int age) {
m_Name = name;
m_Age = age;
}
bool operator==(Person &p) {
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
string m_Name;
int m_Age;
};
//调用
Person p1("张三", 18);
Person p2("lisi", 18);
if (p1 == p2) { }
else { }
6.函数调用运算符重载
函数调用运算符()也可以重载,由于重载后使用的方式非常像函数的调用,因此称为仿函数。
class MyAdd
{
public:
int operator()(int a, int b) {
return a + b;
}
};
//调用
MyAdd myadd;
int res = myadd(100,100);
//匿名对象调用
cout << MyAdd()(100, 100) << endl;
|