简体   繁体   English

如何访问嵌套的 class 的私有成员?

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

A.hpp海参

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

A.cpp A.cpp

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

The private variable is getting set at some place and I want to access that value in this alpha function. How can I access x inside alpha() ?私有变量在某个地方设置,我想在这个alpha function 中访问该值。如何在alpha()中访问x

EDIT: 2nd Question: A.hpp编辑:第二个问题: A.hpp

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

C.hpp C.hpp

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

C.cpp C.cpp

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

You can make class A a "friend" of class B which allows A to access private members of B您可以让 class A成为 class B的“朋友”,这样A就可以访问B的私有成员

combining your files for ease of compilation:合并您的文件以便于编译:

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

A class can access another class's private members if it's a friend of that other class, like in this example:如果 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