【问题标题】:How private members are accessed in derived class C++ [duplicate]如何在派生类 C++ 中访问私有成员 [重复]
【发布时间】:2018-03-24 19:35:46
【问题描述】:

我发现了以下东西:-

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

但是在运行以下程序时,派生类正在访问基类的私有数据成员,如何以及为什么

程序如下:-

#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 ;
}

【问题讨论】:

  • 不,它没有访问基类的私有成员。它访问的所有基类成员函数都在公共范围内。
  • “基类的私有成员永远不会被子类继承。” 不正确。它们是继承的,但从派生类中不可见。

标签: c++


【解决方案1】:

我发现了以下东西:-

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2011-08-23
    • 2012-05-26
    • 1970-01-01
    • 2017-08-07
    • 2021-07-01
    相关资源
    最近更新 更多