Making a class friend itself

霸气de小男生 提交于 2019-12-07 17:33:15

问题


EDIT: It looks like I'm completely misinformed. Please close this thread. Gah.

For the record, the following compiles and works:

class ForeverAlone
{
private:
  int m_friends;
  HANDLE m_handle;

public:
  ForeverAlone()
  {
    m_handle = CreateThread(NULL, 0, &ForeverAlone::SadThread, reinterpret_cast<void*>(this), 0, NULL);
  }

  ~ForeverAlone()
  {
    if (m_handle != NULL)
      CloseHandle(m_handle);
  }

protected:
  static unsigned long WINAPI SadThread(void* param)
  {
    ForeverAlone* thisObject = reinterpret_cast<ForeverAlone*>(param);

    // is there any way for me to access:
    thisObject->m_friends;
  }
};

Original question: I have a static protected thread method, which I pass an object to. Can I somehow make the class friend itself so I can access its private members?


回答1:


All class methods, static or not, are automatically "friends" of the class. Friend is used to allow external functions and classes access to a class. The class is always its own "friend".




回答2:


Do this:

extern "c"  DWORD  __stdcall CInterfaceSadThread(LPVOID lpThreadParameter);

class ForeverAlone
{
  private:
    int m_friends;
    HANDLE m_handle;

  public:
    ForeverAlone()
    {
      m_handle = CreateThread(NULL, 0, 
                              &CInterfaceSadThread,
                              //
             // You may get arguments about using static_cast here
             // I still prefer reinterpret_cast as it makes it stick out
             // Thus I check it more carefully when I see it.
             // For this situation it works correctly
             // As casting to void* and back to the original are guaranteed.
                              reinterpret_cast<void*>(this), 
                              0, NULL);
    }

    ~ForeverAlone()
    {
      if (m_handle != NULL)
        CloseHandle(m_handle)
    }

  protected:
    friend DWORD  CInterfaceSadThread(LPVOID lpThreadParameter);
    DWORD WINAPI SadThread()
    {
      // Do Stuff here
      // Note: Just because you get here does not mean that the object is finished
      //       initializing. The parent thread may have been suspended after this
      //       one was created. Thus checking the state of member variables at this
      //       point is dangerous unless you can guarantee that construction has finished

      return result;
    }
};

Then in the callback just access your function;

extern "c" DWORD __stdcall  CInterfaceSadThread(LPVOID lpThreadParameter)
{
    // Note: You can only cast back to ForeverAlone* so be carefull
    //       Hence I use reinterpret_cast as this forces me to double check.
    ForeverAlone*  alone = reinterpret_cast<ForeverAlone*>(lpThreadParameter);
    return alone->SadThread();
}


来源:https://stackoverflow.com/questions/8686342/making-a-class-friend-itself

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