如何在派生类C ++中访问私有成员

时间:2018-03-24 19:35:46

标签: c++

我找到了以下内容: -

继承中的公共模式:如果我们从公共基类派生一个子类。然后,基类的公共成员将在派生类中变为公共成员,并且基类的受保护成员将在派生类中受到保护。基类的私有成员永远不会在子类中继承。

但是在运行以下程序时,派生类正在访问基类的私有数据成员, HOW AND WHY

该计划如下: -

#include<iostream>
using namespace std ;

class Student
{
  private  :  long int sapId ;
              char name[20] ;

  public   : void getStudent()
             {
               cout << "Enter The Sap Id :- " ;
               cin >> sapId ;
               cout << "Enter The Name of The Student :- " ;
               cin >> name ;
             }

             void putStudent()
             {
               cout << "SAP ID :- " << sapId << endl ;
               cout << "Name :- " << name << endl ;
             }
} ;

class CSE : public Student
{
  protected : char section ;
              int rollNo ;

  public    : void getCSE()
              {
                cout << "Enter Section :- " ;
                cin >> section ;
                cout << "Enter Roll Number :- " ;
                cin >> rollNo ;
              }

              void putCSE()
              {
                cout << "Section :- " << section << endl ;
                cout << "Roll Number :- " << rollNo << endl ;
              }
} ;

main()
{
  CSE obj ;
  obj.getStudent() ;
  obj.getCSE() ;
  cout << endl ;
  obj.putStudent() ;
  obj.putCSE() ;
  return 0 ;
}

1 个答案:

答案 0 :(得分:1)

  

我找到了以下内容: -

     

继承中的公共模式:如果我们从公共基类派生一个子类。然后,基类的公共成员将在派生类中变为公共成员,并且基类的受保护成员将在派生类中受到保护。基类的私有成员永远不会在子类中继承。

事情是错的。就这么简单。

正如您所发现的那样,私人成员就像其他所有成员一样继承。

放下引用的书并选择另一本书。