赋值运算符重载
#include <iostream>
using namespace std;
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;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p2 = p1;
p3 = p2 = p1;
cout << "p1的年龄为:" << *p1.m_Age << endl;
cout << "p2的年龄为:" << *p2.m_Age << endl;
}
int main()
{
test01();
cout << "\n " << endl;
system("pause");
return 0;
}
关系运算符重载
#include <iostream>
using namespace std;
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;
}
return false;
}
bool operator!=(Person& p)
{
if (this->m_name != p.m_name || this->m_age != p.m_age)
{
return true;
}
return false;
}
string m_name;
int m_age;
};
void test01()
{
Person p1("Tom", 18);
Person p2("Tom", 18);
if (p1 == p2)
{
cout << "p1和p2是相等的" << endl;
}
else
{
cout << "p1和p2是不相等的" << endl;
}
if (p1 != p2)
{
cout << "p1和p2是不相等的" << endl;
}
else
{
cout << "p1和p2是相等的" << endl;
}
}
int main()
{
test01();
cout << "\n " << endl;
system("pause");
return 0;
}
函数调用运算符重载
#include <iostream>
using namespace std;
class MyPrint
{
public:
void operator()(string test)
{
cout << test << endl;
}
};
void MyPrint02(string test)
{
cout << test << endl;
}
void test01()
{
MyPrint myPrint;
myPrint("hello world");
MyPrint02("hello world2");
}
class MyAdd
{
public:
int operator()(int num1 ,int num2)
{
return num1 + num2;
}
};
void test02()
{
MyAdd myadd;
int result = myadd(100, 100);
cout << "result= " << result << endl;
cout << MyAdd()(100, 100) << endl;
}
int main()
{
test01();
cout << "\n " << endl;
test02();
cout << "\n " << endl;
system("pause");
return 0;
}