【发布时间】:2013-11-30 04:52:14
【问题描述】:
我的理解是静态成员函数可以访问类的私有的、受保护的成员。 在我的代码中,sortPoint2DXAsc 应该能够访问 X 和 Y,因为它是 Point2D 的成员函数。但我得到这个错误:
Point2D.h: In function ‘bool sortPoint2DXAsc(const Point2D&, const Point2D&)’:
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:21: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:31: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:44: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:55: error: within this context
Point2D.h:23:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:41:67: error: within this context
Point2D.h:23:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:41:77: error: within this context
这是我的代码:
class Point2D
{
protected:
int x;
int y;
public:
//Constructor
Point2D();
Point2D (int x, int y);
//Accessors
int getX();
int getY();
//Mutators
void setX (int x);
void setY (int y);
static bool sortPoint2DXAsc (const Point2D& left, const Point2D& right);
};
bool sortPoint2DXAsc (const Point2D& left, const Point2D& right)
{
return (left.x < right.x) || ((left.x == right.x) && (left.y < right.y));
}
【问题讨论】:
-
该函数不是类的一部分。改为
bool Point2D::sortPoint2DXAsc... -
哇,感谢您指出这一点。不知道我是怎么错过的。
标签: c++ function static protected