【发布时间】:2017-12-29 23:38:46
【问题描述】:
目标很简单,我有一个具有宽度、高度和面积属性的Rectangle 类。我为< 运算符创建了一个运算符重载,因为这就是std::sort 用于比较的内容。
根据我目前在网上发现的情况,似乎这个问题通常源于类的复制运算符或构造函数中的某些错误。
这是Rectangle 类的复制构造函数:
Rectangle::Rectangle(const Rectangle & other)
{
m_width = other.m_width;
m_height = other.m_height;
m_area = other.m_area;
}
这是我的复制操作符:
Rectangle & Rectangle::operator=(const Rectangle & rhs)
{
if (this != &rhs)
{
m_width = rhs.m_width;
m_height = rhs.m_height;
}
return *this;
}
这里是< 运算符:
bool Rectangle::operator<(const Rectangle & rhs)
{
return (m_area > rhs.m_area);
}
最后,这是我如何调用 sort 方法,以防万一:
// rects is a vector<Rectangle> with several rectangles in it
std::sort(rects.begin(), rects.end());
我认为我所做的一切都是正确的,但感谢任何帮助!
【问题讨论】:
-
你让编译器为你实现复制构造和赋值。它不太可能引入琐碎的错误。
-
为什么不在赋值运算符中复制区域?
-
你的问题无法从那个 sn-ps 重现 => 没有帮助
标签: c++ copy operator-overloading