簡體   English   中英

如何訪問嵌套的 class 的私有成員?

[英]How to access private members of a nested class?

海參

class A
{
  public:
  class B
  {
    int x;
  public:
    B(int f);
  };
  void alpha(B *random);
};

A.cpp

void A::alpha(A::B *random)
{  
  // access x here, how to do it?
}

私有變量在某個地方設置,我想在這個alpha function 中訪問該值。如何在alpha()中訪問x

編輯:第二個問題: A.hpp

class A
{
  public:
  class B
  {
    int x;
  public:
    B(int f);
  };
  virtual void alpha(B *random) = 0;
};

C.hpp

class C : public A
{
  public:
  virtual void alpha(B *random);
};

C.cpp

void C::alpha(A:B *random)
{  
  // access x here, how to do it? 
}

您可以讓 class A成為 class B的“朋友”,這樣A就可以訪問B的私有成員

合並您的文件以便於編譯:

class A
{
  public:
  class B
  {
    friend class A;  // *** HERE ***
    int x;
  public:
    B(int f);
  };
  void alpha(B *random);
};



void A::alpha(B *random)
{
    int x = random->x;
}

int main() {}

如果 class 是另一個 class 的friend元,則它可以訪問另一個類的private成員,如下例所示:

class A {
 public:
  class B {
    friend class A;
    int x;

   public:
    B(int f);
  };
  void alpha(B *random) { random->x = 10; }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM