无法访问静态方法中的私有类成员? [英] Can't access private class members inside of static method?
问题描述
我有以下设置:
//。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 {
SetPixel(dc,mCellStartingPoint.x + i,mCellStartingPoint + yoff,red);但是,在实现DrawRowOfPixels()方法时,如果你使用了DrawRowOfPixels()方法,那么你可以使用DrawRowOfPixels .cpp文件,我在Cell类的所有成员变量中获取错误。 (即mCellStartingpoint,mXoffset和mYoffset)
错误C2228:.x的左边必须有class / struct / union
错误C2597:非法参考非静态成员Cell :: mXoffset
错误C3867: mXoffset':函数调用缺少参数列表;使用'& Cell :: mXoffset'创建指向成员的指针
错误:非静态成员引用必须与特定对象相关
我知道我可能做的东西真的很蠢,但这里发生了什么?为什么我不能在我的静态成员函数中使用我的私有成员变量,我应该能够?
解决方案在 static
方法内部的非静态成员,除非您明确地在成员函数内部提供对象实例(将对象实例显式地作为参数传递,或使用全局实例可以在函数内访问)
对于非静态成员函数,隐式的 this
作为函数的第一个参数传递。 此
指针在成员函数内引用以访问成员。 static
成员不通过隐式的这个
指针,所以你不能访问非静态成员函数内,除非你明确得到成员函数中的对象。
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?
解决方案 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.
这篇关于无法访问静态方法中的私有类成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!