【问题标题】:Static member function cannot access protected member of class静态成员函数无法访问类的受保护成员
【发布时间】: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


【解决方案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-&gt;x 而不是 left.getX(),您会收到错误消息,因为您的函数是静态的。

现在,这是一个second example,您可以在其中访问xy,而无需访问器。 由于您在您的类定义中,xy 可以从 leftright 访问,它们是 Point2D 的实例,即使它们受到保护。

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 2011-01-02
    • 2011-09-27
    • 2014-01-30
    • 2017-08-01
    • 2016-10-01
    • 2016-07-05
    相关资源
    最近更新 更多