我的理解是静态成员函数可以访问类的受保护成员。 在我的代码中,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));
}
答案 0 :(得分:1)
我想你想要像this code tested这样的东西:
class Point2D {
protected:
int x;
int y;
public:
//Constructor
Point2D();
Point2D (int x, int y);
//Accessors
int getX() const {return x; }
int getY() const {return y;}
//Mutators
void setX (int x) {/*Do something with x*/}
void setY (int y) {/*Do something with y*/}
static bool sortPoint2DXAsc(const Point2D& left, const Point2D& right);
};
bool Point2D::sortPoint2DXAsc (const Point2D& left, const Point2D& right)
{
return (left.getX() < right.getX()) || ((left.getX() == right.getX()) && (left.getY() < right.getY()));
}
您可以使用静态,因为您在函数中没有使用this
。例如,如果您使用this->x
而不是left.getX()
,则会收到错误,因为您的函数是静态的。
现在,这是一个second example,您无需访问者即可访问x
和y
。
由于您位于班级定义中,x
和y
可以从left
和right
访问,这些Point2D
是{{1}}的实例,即使它们受到保护。< / p>