1. 关系运算符重载
- 自定义数据类型 不会内部做 比较 == !=
- 所以要重载 == !=
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->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;
}
public:
string m_Name;
int m_Age;
};
void test01()
{
Person p1("小米", 10);
Person p2("小强", 15);
Person p3("小强", 15);
/*int a = 10;
int b = 10;
if (a == b)
{
cout << "a b相等" << endl;
}*/
if (p1 == p2)
{
cout << "p1和p2相等" << endl;
}
else
{
cout << "p1和p2不相等" << endl;
}
if (p1 != p2)
{
cout << "p1和p2不相等" << endl;
}
else
{
cout << "p1和p2相等" << endl;
}
if (p3 == p2)
{
cout << "p3和p2相等" << endl;
}
else
{
cout << "p3和p2不相等" << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
2.函数调用运算符重载
- () 仿函数 对象 () 看似像函数调用
- MyAdd() 匿名对象
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//()重载
class MyPrint
{
public:
void operator()(string text)
{
cout << text << endl;
}
};
void test01()
{
MyPrint myPrint;
myPrint("hello world"); //仿函数
}
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
void test02()
{
/*MyAdd myAdd;
cout << myAdd(1, 2) << endl;*/
cout << MyAdd()(1, 1) << endl; //匿名对象
}
int main()
{
//test01();
test02();
system("pause");
return 0;
}