Can't access private class members inside of static method?

不羁的心 提交于 2019-12-08 08:13:06

问题


I have the following setup:

//.h
class Cell
{
private:
    POINT   mCellStartingPoint;
    int     mXoffset;
    int     mYoffset;
public:
    static void DrawRowOfPixels(int yoff);
    Cell();
    ~Cell();
};

//.cpp
void Cell::DrawRowOfPixels(int yoff)
{
    HDC dc = GetDC(NULL);
    COLORREF red = 0xFF0000;
    for(int i = mCellStartingPoint.x; i < mXoffset; i++)
    {
        SetPixel(dc, mCellStartingPoint.x + i, mCellStartingPoint + yoff, red);
    }
}

However, when implementing the DrawRowOfPixels() method in the .cpp file, I get errors at all of the member variables of the Cell class. (i.e. mCellStartingpoint, mXoffset, and mYoffset)

error C2228: left of '.x' must have class/struct/union

error C2597: illegal reference to non-static member 'Cell::mXoffset'

error C3867: 'Cell::mXoffset': function call missing argument list; use '&Cell::mXoffset' to create a pointer to member

error: A nonstatic member reference must be relative to a specific object

I know I'm probably doing something really stupid, but what's going on here? Why can't I use my private member variables inside my static member function like I should be able to?


回答1:


You cannot access a non static member inside a static method unless you explicitly make available the object instance inside the member function.(Pass object instance explicitly as argument or use a global instance which can be accessed inside the function)

For a non static member function an implicit this pointer is passed as the first argument to the function. The this pointer is dereferenced inside the member function to access the members. static members are not passed with the implicit this pointer so you cannot access non static members inside the function unless you explicitly get the object inside the member function.



来源:https://stackoverflow.com/questions/15847307/cant-access-private-class-members-inside-of-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!