【发布时间】:2021-06-27 10:34:11
【问题描述】:
从下面截取的代码中,需要访问 A::B 类的成员函数。由于 B 类是私有的,因此无法从非成员函数为其创建对象。请帮助我解决这个问题,而无需将Class B 公开
以下代码供参考
啊.h
#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;
【问题讨论】:
-
你为什么不上课
Bpublic? -
看起来
call_sample是A::B的实现细节,所以将它作为A::B的私有静态成员是有意义的。 -
您打算访问
A::B的哪个实例?单独上课对你没有好处。 (这看起来像 XY problem。) -
很抱歉,由于其他原因,B 类无法公开,因此缺少必要条件