让自己成为一个朋友

时间:2011-12-31 04:46:20

标签: c++ friend

编辑:看起来我完全被误导了。请关闭此帖子。尔加。

为了记录,以下编译和工作:

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;
  }
};

原始问题:我有一个静态保护线程方法,我将对象传递给它。我可以以某种方式创建类friend本身,以便我可以访问其私有成员吗?

2 个答案:

答案 0 :(得分:11)

所有类方法(静态或非静态)都是类的“朋友”。 Friend用于允许外部函数和类访问类。班级总是自己的“朋友”。

答案 1 :(得分:1)

这样做:

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;
    }
};

然后在回调中只访问你的函数;

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();
}