1.赋值运算符重载
浅拷贝与深拷贝的问题
#include <iostream>
using namespace std;
class Person
{
public:
Person(int a)
{
age = new int(a);
}
Person& operator=(Person& p)
{
//赋值要深拷贝
if (age != NULL)
{
delete age;
age = NULL;
}
age = new int (*p.age);
return *this;
}
~Person()
{
if (age != NULL)
{
delete age;
age = NULL;
}
}
public:
int* age;
};
int main()
{
Person p1(20);
Person p2(30);
Person p3(40);
p1 = p2 = p3;
cout << *p1.age << *p2.age << *p3.age << endl;
}
2.关系运算符重载
#include <iostream>
using namespace std;
//关系运算符重载
class Person
{
public:
Person(string name, int age)
{
this->name = name;
this->age = age;
}
bool operator==(Person &p)
{
if (this->age == p.age && this->name == p.name)
{
return true;
}
return false;
}
bool operator!=(Person& p)
{
if (this->age == p.age && this->name == p.name)
{
return false;
}
return true;
}
string name;
int age;
};
int main()
{
Person p1("张三", 18);
Person p2("张三", 18);
if (p1 == p2)
{
}
if (p1 != p2)
{
}
}
3.函数调用运算符重载
仿函数,用起来很灵活,在STL中应用较多。
匿名函数对象 类名()()