我基本上是在尝试编写比较器函数,以x和y的顺序排列对象P1和Pt2的值,按升序和降序排列。
现在我遇到了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));
}
答案 0 :(得分:3)
将该版本与getter一起使用,但将left.pt1.getX()
替换为left.getX()
等。
我猜你在Point2D
课程中需要改变
double getX();
到
double getX() const;
同样适用于getY
。
传递const Point2D& left, const Point2D& right
,您承诺不修改这些对象中的任何值。您只能调用声明为const
的成员函数(它们不会更改对象)。
答案 1 :(得分:0)
bool Line2D::sortLine2DPtAsc (const Point2D& left, const Point2D& right)
您的参数属于Point2D
类型,也许您打算使用Line2D
类型的参数
如果函数是排序线,你为什么要传递点;)
pt1
和pt2
是Line2D
课程的成员而不是您的Point2D
课程