自增运算符重载
#include <iostream>
using namespace std;
class Person {
friend ostream& operator<<(ostream &cout, Person p);
public:
Person(int x) {
m_Age = x;
}
Person& operator++() {
m_Age++;
return *this;
}
Person operator++(int) {
Person temp = *this;
m_Age++;
return temp;
}
private:
int m_Age;
};
ostream& operator<<(ostream &cout,Person p) {
cout << p.m_Age;
return cout;
}
void test1() {
Person p1(10);
cout << ++p1<<endl;
}
void test2() {
Person p1(10);
cout << p1++ << endl;
cout << p1 << endl;
}
int main()
{
test2();
}
赋值运算符重载
#include <iostream>
using namespace std;
class Person {
friend ostream& operator<<(ostream &cout, Person p);
public:
Person(int x) {
m_Age = new int(x);
}
~Person() {
while (m_Age != NULL) {
delete m_Age;
m_Age = NULL;
}
}
Person & operator=(Person& p) {
if (m_Age != NULL) {
delete m_Age;
m_Age = NULL;
}
this->m_Age = new int(*p.m_Age);
return *this;
}
public:
int *m_Age;
};
void test01() {
Person p1(10);
Person p2(20);
Person p3(30);
p3= p2 = p1;
cout << *p1.m_Age << endl;
cout << *p2.m_Age << endl;
cout << *p3.m_Age << endl;
}
int main()
{
test01();
}
关系运算符重载
#include <iostream>
using namespace std;
class Person {
public:
Person(int x,string str) {
m_Age = x;
m_Name = str;
}
~Person() {
}
bool operator==(Person &p) {
if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) {
return true;
}
else {
return false;
}
}
private:
int m_Age;
string m_Name;
};
void test01() {
Person p1(10,"张三");
Person p2(10,"张三");
if (p1 == p2) {
cout << "两个对象相等" << endl;
}
else {
cout << "两个对象不相等" << endl;
}
}
int main()
{
test01();
}