赋值运算符重载:
注意第四点:C++编译器自动生成复制运算符operator=,对属性进行值拷贝;
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题;
P1 = p2;
重载赋值运算符的一个重要原因是在堆区开辟了存储空间;但是赋值的过程中只是进行了浅拷贝(并未再在堆区开辟空间),所以导致堆区的数据重复释放报错;
int a=10,b = 20, c = 30;
a = b = c;
p1 = p2 = p3;
为了解决上述问题,所以重载赋值运算函数要放回引用类型;
关系运算符重载:
作用:重载关系运算符,可以让两个自定义类型对象进行对比操作;
class Person {
public:
bool operator==(Person &p) {
if (this->age == p.age&&this->sex == p.sex) {
return true;
}
return false;
}
Person(int age,string sex) {
this->age = age;
this->sex = sex;
}
private:
int age;
string sex;
};
int main() {
Person p1(18, "李四");
Person p2(18,"王五");
if (p1 == p2) {
cout << "这两个人的年龄和名字相符;"<<endl;
}
else {
cout << "这两个人的年龄和名字不相符;"<<endl;
}
system("pause"); //暂停一下以便查看
return 0; //标准的返回退出
}
重载"==“和”!="相似;
函数调用运算符重载
- 函数调用运算符 () 也可以重载
- 由于重载后使用的方式非常像函数的调用,因此称为仿函数
- 仿函数没有固定写法,非常灵活
class MyPrint {
public:
void operator()(string text) {
cout << text << endl;
}
};
class MyAdd {
public:
int operator()(int a, int b) {
return a + b;
}
};
int main() {
MyPrint print;
print("加油");
MyAdd add;
int sum = add(100, 50);
cout << "sum = "<<sum << endl;
匿名函数对象——MyPrint(),MyAdd()
//cout << MyPrint()("你好啊!") << endl;————因为没有返回值,所以没有输出不能使用
cout << MyAdd()(10, 20) << endl;
return 0; //标准的返回退出
}
注:可以使用匿名对象进行调用;