如何从非成员函数访问私有类变量

时间:2021-03-31 11:53:47

标签: c++ class private

从下面截取的代码中,需要访问类A::B的成员函数。由于类 B 是私有的,因此无法从非成员函数为其创建对象。请帮助我解决此问题,而无需将 Class B 公开

以下代码供参考

#include <iostream>

class A
{
public:
  A();
  void Func();
private:
  class B;
  B *b;
};

A.cpp

#include "A.h"
#include "AB.h"

A::A()
{
    b = new B(this);
}
void A::Func()
{
    b->Func();
}

AB.h

#include "A.h"

class A::B
{
public:
  B(A* a);
  void Func();
private:
  A* ptr;

};

AB.cpp

#include "AB.h"

A::B::B(A* a):ptr(a)
{

}

void A::B::Func()
{
    std::cout<<"Do nothing ";
}
static void call_sample()
{
    A::B* tmp;
    //access member function of class A::B
}

以下错误供参考:

In file included from AB.cpp:2:0:
AB.h: In function ‘void call_sample()’:
AB.h:3:10: error: ‘class A::B’ is private
 class A::B
          ^
AB.cpp:15:4: error: within this context
 A::B* tmp;

1 个答案:

答案 0 :(得分:2)

B 是来自 A 的嵌套类,它是私有的,因此,作为定义,它不能从外部访问。如果需要使用B,可以在B的公共部分decleare A,然后可以使用A::B*类型。