gpt4 book ai didi

c++ - 从比较函数访问成员变量/getter

转载 作者:行者123 更新时间:2023-11-30 02:50:57 26 4
gpt4 key购买 nike

我基本上是在尝试编写比较器函数,以按升序和降序对对象 P1 和 Pt2 的 x 然后 y 值进行排序。

现在我遇到了 x 和 y protected 错误,但是请问我如何正确使用 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));
}

最佳答案

使用带有 getter 的版本,但将 left.pt1.getX() 替换为 left.getX()

我猜想在您的 Point2D 类中,您需要更改

double getX();

double getX() const;

getY 也是如此。

被传递 const Point2D& left, const Point2D& right,您根据契约(Contract)不得修改这些对象中的任何值。您只能调用声明为 const 的成员函数(它们不会更改对象)。

关于c++ - 从比较函数访问成员变量/getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com