【发布时间】:2013-11-17 07:08:42
【问题描述】:
我基本上是在尝试编写比较器函数,以按升序和降序排列对象 P1 和 Pt2 的 x 和 y 值。
现在我遇到了一个错误,即 x 和 y 受到保护,但是如何在排序中正确使用 getter? 我还是很困惑。我尝试使用它,但不起作用。
bool Line2D::sortLine2DPtAsc (const Point2D& left, const Point2D& right)
{
return (left.pt1.getX() < right.pt1.getX()) || ((left.pt1.getX() == right.pt1.getX()) && (left.pt1.getY() < right.pt1.getY()));
}
使用 getter 时出错:
Line2D.cpp:25:15: error: ‘const class Point2D’ has no member named ‘pt1’
Line2D.cpp:25:34: error: ‘const class Point2D’ has no member named ‘pt1’
Line2D.cpp:25:56: error: ‘const class Point2D’ has no member named ‘pt1’
Line2D.cpp:25:76: error: ‘const class Point2D’ has no member named ‘pt1’
Line2D.cpp:25:97: error: ‘const class Point2D’ has no member named ‘pt1’
Line2D.cpp:25:116: error: ‘const class Point2D’ has no member named ‘pt1’
这是我的代码:
class Line2D
{
private:
Point2D pt1;
Point2D pt2;
public:
//Constructor
Line2D ();
Line2D (Point2D pt1, Point2D pt2);
//Accessors
Point2D getPt1();
Point2D getPt2();
double getScalarValue(); //returns the value of attribute length
//Mutators
void setPt1 (Point2D pt1);
void setPt2 (Point2D pt2);
static bool sortLine2DPtAsc (const Point2D& left, const Point2D& right) ;
}
bool Line2D::sortLine2DPtAsc (const Point2D& left, const Point2D& right)
{
return (left.x < right.x) || ((left.x == right.x) && (left.y < right.y));
}
【问题讨论】:
-
今天显然是一个模棱两可的“它不起作用”问题的日子,没有详细说明这意味着什么。不编译?不像你想要的那样排序?挂起?崩溃?我打赌保罗的答案是正确的,你应该看看它。请更具体,特别是如果它是编译器或运行时 error 消息,在这种情况下,请在您的问题中包含 entire 消息 verbatim。
-
你去。优秀的留言。那么我能问一下什么是可能令人尴尬的问题吗?您要排序的点集合是什么?除非我弄错了,否则您正在对
Line2D对象的集合进行排序,对吗?每个都有两点?这可以解释很多。 -
@WhozCraig 我已修改为 bool Line2D::sortLine2DPtAsc (const Line2D& left, const Line2D& right) 并成功编译。谢谢。
标签: c++ sorting vector comparator accessor