如何使派生类访问私有成员数据? [英] How to make a derived class access the private member data?

查看:62
本文介绍了如何使派生类访问私有成员数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了c ++问题.我有一个基类,在该类的私有可见性区域内有一个自引用对象指针.我在基类中有一个构造函数,用于初始化这两个指针.现在,我有了派生类,其访问说明是私有的(我想将基类的公共成员函数设为私有).现在,通过派生类的成员函数,我想创建一个对象指针,该对象指针可以指向基类的私有数据,即那些自引用对象指针.我的代码是:

I'm stuck with a c++ problem. I have a base class that has a self referential object pointer inside the private visibility region of the class. I have a constructor in the base class that initializes these two pointers. Now I have my derived class whose access specifier is private(I want to make the public member functions of my base class private). Now through the member functions of my derived class I want to create an object pointer which can point to the private data of the base class, that is ,those self referential object pointers. My code is:

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. 
}

推荐答案

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

Derived class can not access the private members of it's base class. No type of inheritance allows access to private members.

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

However if you use friend declaration you can do that.

这篇关于如何使派生类访问私有成员数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆