我的理解是静态成员函数可以访问类的私有(private)、 protected 成员。 在我的代码中,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));
}
最佳答案
我想你想要类似 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()));
}
您可以使用 static,因为您没有在函数中使用 this
。例如,如果您使用 this->x
而不是 left.getX()
,您会收到错误,因为您的函数是静态的。
现在,这是一个 second example您可以在没有访问器的情况下访问 x
和 y
。
由于您位于类定义中,因此可以从 left
和 right
访问 x
和 y
,它们是Point2D
即使它们受到保护。
关于c++ - 静态成员函数无法访问类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024064/