关系运算符
关系运算符重载可以实现自定义类型的比较
code:
#include
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66