我卡在一个c + +的问题。我有一个基类,在类的私有可见性区域内有一个自引用对象指针。我在初始化这两个指针的基类中有一个构造函数。现在我有我的派生类,其访问说明符是私有的(我想让我的基类的公共成员函数是私有的)。现在通过派生类的成员函数,我想创建一个对象指针,它可以指向基类的私有数据,也就是那些自引用对象指针。我的代码是:如何让派生类访问私有成员数据?
class base{
private:
base *ptr1;
int data;
public:
base(){}
base(int d) { data=d }
};
class derived:private base{
public:
void member()
};
void derived::member()
{
base *temp=new base(val); //val is some integer
temp->ptr1=NULL; //I can't make this happen. To do this I had to declare all the
//private members of the base class public.
}
使用'protected'而不是'private'? –
为'private'成员设置一个受保护的getter?但是,如果你需要这样的解决方案,通常你的设计是有缺陷的。 –
这也行不通。编译器错误。也试过了。只有公开我可以访问它。但是这会使代码易受攻击。 –