c++ - 静态成员函数无法访问类的 protected 成员

标签 c++ function static protected

我的理解是静态成员函数可以访问类的私有(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您可以在没有访问器的情况下访问 xy 。 由于您位于类定义中,因此可以从 leftright 访问 xy,它们是Point2D 即使它们受到保护。

关于c++ - 静态成员函数无法访问类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024064/

相关文章:

c++ - glulookat() 用法-opengl 和 C++

c++ - C++20 中弃用的 lambda 捕获

objective-c - 为什么 NSMakePoint 在程序的一处失败而在其他地方工作?

programming-languages - 不同语言的静态

用于读取结构的基于 C++ 范围的循环

c++ - 虚拟继承、显式实例化——返回派生类引用/指针(协变类型)

swift - swift 函数的外部名称有什么好处?

javascript - 允许 `p.foo = o.foo` 返回对函数 `foo` 的引用的 javascript 机制/规则是什么?

java - 警告 : The type parameter E is hiding the type E when using an inner class

java - 并发访问静态方法