2013-09-22 78 views
6

我卡在一个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. 
} 
+8

使用'protected'而不是'private'? –

+4

为'private'成员设置一个受保护的getter?但是,如果你需要这样的解决方案,通常你的设计是有缺陷的。 –

+0

这也行不通。编译器错误。也试过了。只有公开我可以访问它。但是这会使代码易受攻击。 –

回答

11

派生类无法访问其基类的私有成员。没有任何类型的继承允许访问私有成员。

但是,如果您使用friend声明,你可以这样做。

+0

我知道,但没有办法做到这一点。唯一的其他选择是使用朋友类。但我想用继承来解决问题。 –

+3

你可以使用朋友声明!或更好地使用保护,而不是私人:) –

4

没有其他方式访问其他班级的私人数据,然后友谊。然而,你可以用继承来做什么,就是访问基类的受保护数据。但这并不意味着您可以访问基本类型的另一个对象的受保护数据。您只能访问受保护的派生类的底座部分的数据:

class base{ 
protected: //protected instead of 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(3); 
    //temp->ptr1 = 0; //you need friendship to access ptr1 in temp 

    this->ptr1 = 0; // but you can access base::ptr1 while it is protected 
} 

int main(){} 
+0

感谢您的帮助 –

2

尽量给保护作为基类的访问说明符和继承的私人模式的基类.....但进一步使用基类u的成员函数可能需要很少的短内联函数,因为它们也将转换为私有文件

相关问题