访问派生类中的私有成员 [英] access private members in derived class

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

问题描述

嗨 在以下代码中,为什么派生类可以在我是私有成员且私有成员不访问Derive的情况下访问基类i成员?




  class 基本{
     int  i;
受保护的:
     int  read(){返回 i; }
    无效 集合( int  ii){i = ii; }
公共:
    Base(){i =  0 ; }
     int  ( int  m){返回 m * i; }
};
派生: public 基数{
     int  j;
公共:
    Derived(){j =  0 ; }
    无效更改( int  x){ set  (X); cout<<读(); }
    
};
 int  main(){
    派生d;
    d.change( 10 );
    返回  0 ;
} 



[edit]已对代码块进行排序-OriginalGriff [/edit]

解决方案

因为它通过方法set访问i:因此可以访问protected来自Derived.


这是不正确的:私有成员不派生".这甚至不是假的,只是没有意义. :-)
成员不能派生",只有类型可以.所有成员都是继承的,没有排除.

—SA


它不能-您的代码段在派生的cals中没有引用"i",如果尝试,您将获得一个编译错误:

class Derived : public  Base {
    int j;
public:
    Derived() { j=i; }
    void change(int x) { set(x); cout << read(); }
   
}

礼物:

error C2248: ''Base::i'' : cannot access private member declared in class ''Base''


hi in the following code why derived class can access to Base class i member while i is private and private members doesn''t Derive ?




class Base {
    int i;
protected:
    int read() { return i; }
    void set(int ii) { i = ii; }
public:
    Base() { i=0; }
    int value(int m) { return m*i; }
};
class Derived : public  Base {
    int j;
public:
    Derived() { j=0; }
    void change(int x) { set(x); cout << read(); }
    
};
int main() {
    Derived d;
    d.change(10);
    return 0;
}



[edit]Code block sorted - OriginalGriff[/edit]

解决方案

Because it accesses i via the method set: such method is protected hence accessible from Derived.


This is not true: "private members doesn''t Derive". This is not even false, just makes no sense. :-)
A member can not "derive", only a type can. All members are inherited, no exclusions.

—SA


It can''t - your code frqgment does not refer to "i" in your derived calss, and if you try you will get a compilation error:

class Derived : public  Base {
    int j;
public:
    Derived() { j=i; }
    void change(int x) { set(x); cout << read(); }
   
}

Gives:

error C2248: ''Base::i'' : cannot access private member declared in class ''Base''


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

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