静态成员函数无法访问类的受保护成员

时间:2013-11-16 21:22:15

标签: c++ function static 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));
}

1 个答案:

答案 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,您无需访问者即可访问xy。 由于您位于班级定义中,xy可以从leftright访问,这些Point2D是{{1}}的实例,即使它们受到保护。< / p>