【发布时间】:2020-04-17 09:45:33
【问题描述】:
为什么一组自定义类(比如说 Person)上的 find() 函数调用不等式运算符 '<' 而不是 '==' 。为了说明,我有以下代码,我在一组 Person 类上调用 find 函数(请参阅 test2())。 .
#include<iostream>
#include<stdio.h>
#include<string>
#include<set>
using namespace std ;
class Person {
friend ostream & operator<<(ostream &os , const Person p) ;
string name ;
int age;
public :
Person()
:name{"Unknown"}, age{0}{
}
Person(string name , int age )
:name{name}, age{age}
{
}
//OVERLOADED operators
bool operator<(const Person &rhs) const;
bool operator ==(const Person &rhs) const;
};
bool Person::operator<(const Person &rhs) const{
cout<<" < operator called"<<endl;
return this->age < rhs.age;
}
bool Person::operator==(const Person &rhs) const{
cout<<"Equality operator"<<endl;
return (this->age == rhs.age && this->name == rhs.name);
}
ostream & operator<<( ostream &os , const Person p ){
os<<p.name <<":"<<p.age<<endl;
return os;
}
template<class T>
void display(const set<T> &s1){
for (const auto &temp : s1){
cout<<temp <<" ";
}
cout<<endl;
}
void test2(){
cout<<"====================TEST2=========="<<endl;
set<Person> stooges {
{"Larry",2},
{"Moe",1},
{"Curly",3},
};
cout<<"Something random "<<endl;
auto it = stooges.find(Person{"Moe",1}); //Calls the '<' operator
}
int main(){
test2();
return 0;
}
我还在重载运算符 '<' 和 '==' 的定义中编写了 cout 语句。
输出内容为:
====================TEST2==========
< operator called
< operator called
< operator called
< operator called
< operator called
Something random
< operator called
< operator called
< operator called
Hit any key to continue...
【问题讨论】:
-
要求是可以对集合中键的元素进行排序,即通过根据某些标准比较它们以某种顺序一致地放置。如果唯一的比较方法是
==,则不可能这样做。考虑一个包含三个键的集合,"A"、"B"和"C"。"A" == "B"、"A" == "C"和"B" == "C"的比较都将比较为 false - 这根本没有提供有关如何将它们排序为任何顺序的信息。而比较"A" < "B"、"A" < "C"和"B" < "C"确实提供了有关如何订购它们的信息。 -
除了排序之外,请注意,等价是比等价更弱的条件,并且要求定义等价将是不必要的限制。