C++ 操作员'<'的过载不是每次都使用
C++ Overloading of operator '<' is not being used every time
我有一个person对象,它具有名称、姓氏等属性。我还有3-4个从person类继承的类。
我有另一个类,它将按升序打印所有不同类型的人。因此,我已经重载了运算符'<'我知道它和我在其他地方使用过的一样有效。但由于某种原因,它没有被用于另一个类中的特定方法。
这是我在person类中找到的重载方法。
bool person::operator< ( const person &p2 ) const
{
if ( surname() < p2.surname() )
return true;
else
//There are many other conditions which return true or false depending on the attributes.
}
这是在另一个类(一个子类)中找到的方法,该类应该使用重载运算符,但似乎没有使用它
vector<person *> contacts::sorted_contacts() const{
vector<person *> v_contact;
auto comparison = [] ( person *a, person *b ){ return a < b ; };
//Some code here which fills in the vector
sort(begin(v_contact), end(v_contact), comparison);
}
这里的排序不起作用。因为,当我使用复制/粘贴重载的实现并将其放在这里时,向量是正确排序的。因为我想重用代码,所以我试图弄清楚为什么这里没有使用运算符<
。
此处为
auto comparison = [] ( person *a, person *b ){ return a < b ; }
您正在比较指针,而不是比较对象本身。
为了比较实际对象(这显然是你的意图),你必须取消引用指针。这也是有意义的const合格你的指针正确
auto comparison = [] ( const person *a, const person *b ){ return *a < *b ; }
auto comparison = [] ( person *a, person *b ){ return a < b ; }
比较指针,而不是人。
auto comparison = [] ( person *a, person *b ){ return *a < *b ; }
将比较这些人。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- C++ 与操作员不匹配<<
- 模板操作员&lt;未打电话
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- 为什么“操作员”需要const但不是为“运营商&lt;”
- 左角支架解释为操作员&lt;而不是模板参数
- 超载操作员&lt;&lt; - 必须是二进制操作员
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- &lt;&lt;&lt;的这些超载有什么区别操作员
- (C 14)操作员&lt;&lt;超负荷无法正如智能指针向量所预期的那样工作
- 带有GMP的CodeBlocks,segfault with&lt;&lt;操作员和MP*_Class
- &lt;&lt;操作员在C 中超载错误
- Visual C 构建器图案插入操作员`&lt;&lt;`样式
- 超载&LT的正确方法;操作员
- 在尝试超载&lt;&lt;时链接错误2005和1169操作员
- C++标准::cout和<<操作员,优先级