关系运算符
关系运算符重载可以实现自定义类型的比较
code:
#include <iostream>
using namespace std;
class Horse
{
private:
int m_age;
string m_color;
public:
Horse(int ref_age, string ref_color)
{
m_age = ref_age;
m_color = ref_color;
}
Horse(const Horse& ref_h)
{
m_age = ref_h.m_age;
m_color = ref_h.m_color;
}
bool operator==(const Horse& ref_h) // 返回自身的引用,链式编程,实现连等操作
{
if (m_age == ref_h.m_age && m_color == ref_h.m_color)
{
return true;
}
else
{
return false;
}
}
bool operator!=(const Horse& ref_h)
{
if (m_age == ref_h.m_age && m_color == ref_h.m_color)
{
return false;
}
else
{
return true;
}
}
void show_info()
{
cout << "age: " << m_age << ", color: " << m_color << endl;
}
};
// 对拷贝构造函数的测试
void test01()
{
Horse h1(0, "white");
Horse h2(h1);
cout << (h1 == h2) << endl;
cout << (h1 != h2) << endl;
}
void main()
{
test01();
system("pause");
}
result:
1
0