在静态函数中无法访问非静态成员
Non-static members not accessible in static function
我定义了一个函数
HRESULT AMEPreviewHandler:: CreateHtmlPreview()
{
ULONG CbRead;
const int Size= 115000;
char Buffer[Size+1];
HRESULT hr = m_pStream->Read(Buffer, Size, &CbRead );
//this m_pStream is not accessible here even it is declared globally. the program is asking me to
// declare it static because this CreateHtmlPreview() function called
//inside the Static function (i mean here :-static CreateDialogWM_CommandCreateHtmlPreview();)
//but if i declare it static the two problems arised are
//(1.) It is not able to access the value of the m_pStream which is defined globally.
//(2.)If i declare it static globally then there are so many other function which are using this
// value of m_pStream are not able to access it because they are non static.
}
在我的程序中,它被声明为静态,如下所示:
static HRESULT CreateHtmlPreview(); //i have declared it static because i am calling this function from DialogProc function.If i dont create it static here it dont work
//The function CreateHtmlPreview() is called inside the DialogProc function like this-
BOOL CALLBACK AMEPreviewHandler::DialogProc(HWND m_hwndPreview, UINT Umsg, WPARAM wParam, LPARAM lParam)
{......
case WM_COMMAND:
{
int ctl = LOWORD(wParam);
int event = HIWORD(wParam);
if (ctl == IDC_PREVIOUS && event == BN_CLICKED )
{
CreateHtmlPreview(); //here i am calling the function
return 0;
}
}
}
那么,如何使非静态m_pStream
的值在静态CreateHtmlPreview()
函数定义中可访问呢?
在静态类函数中,您只能访问静态类成员。
如果使CreateHtmlPreview()
成为一个自由函数会怎样?
如果你让它只创建一个html预览(而不是从流中读取),会怎么样?
void CreateHtmlPreview(const char * buffer, int size)
{
//...
}
然后从proc读取数据,并在DialogProc
中调用它
//...
m_pStream->Read(Buffer, Size, &CbRead );
CreateHtmlPreview(Buffer, Size);
不过,您可能需要让函数返回预览才能使用。
你确实说你需要让它成为
静态,因为我正在从DialogProc函数调用此函数
但是,DialogProc不是静态的(在您发布的代码中),所以我看不出会有什么问题。
难道不能直接将m_pStream var作为函数参数传递吗?
而不是用这种方式定义功能
HRESULT AMEPreviewHandler:: CreateHtmlPreview()
{
ULONG CbRead;
const int Size= 115000;
char Buffer[Size+1];
HRESULT hr = m_pStream->Read(Buffer, Size, &CbRead );
}
你可以这样做(你应该定义流类型!)
HRESULT AMEPreviewHandler:: CreateHtmlPreview(stream)
{
ULONG CbRead;
const int Size= 115000;
char Buffer[Size+1];
HRESULT hr = stream->Read(Buffer, Size, &CbRead );
}
并称之为
CreateHtmlPreview(m_pStream);
DoctorLove我已经解决了这个问题,实际上是通过使用这个参数访问非静态变量的想法来解决代码-问题是我没有在WM_INITDIALOG中初始化实例,现在我这样做了-
case WM_INITDIALOG:
{
instance = (AMEPreviewHandler*)lParam;
instance->m_pStream;
return0;
}
而且效果很好。
相关文章:
- 如何在复杂继承中访问静态成员变量
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- decltype:使用指针访问类的静态成员
- 是否通过单元化指针UB访问静态类成员
- 将对象数限制为1可以使用点运算符访问静态成员的1
- 多态性:通过类文本或对象访问静态成员
- 从另一个类访问静态成员函数
- 无法访问静态成员函数C++
- 从外部访问静态成员并通过继承 c++ 访问静态成员
- 通过非静态方法访问静态成员
- 如何在没有对象的情况下访问静态成员 (C++)
- 为什么链接器在内联构造函数中访问静态成员时失败
- 我可以在没有任何前向声明的类/结构上访问静态成员函数吗?
- 访问静态成员函数中的非静态成员的解决方法
- Visual C++ 使用成员选择运算符(. 或 –>)访问静态成员函数
- 使用boost::shared_ptr访问静态成员变量
- 非静态成员函数是否可以访问静态成员函数或数据
- 在c++中显式访问静态成员方法中的静态成员变量
- 无法访问静态成员 ->未解析的外部符号 i
- 通过运算符 [] 访问静态成员unordered_map