c++ - 如何在派生类 C++ 中访问私有(private)成员

标签 c++

<分区>

我发现了以下内容:-

继承中的公共(public)模式:如果我们从公共(public)基类派生子类。然后基类的公共(public)成员将在派生类中变为公共(public)成员,而基类的 protected 成员将在派生类中变为 protected 。基类的私有(private)成员永远不会在子类中被继承。

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

程序如下:-

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

最佳答案

I found the following thing :-

Public mode in inheritance: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. Private members of the base class will never get inherited in sub class.

事情不对。就这么简单。

正如您所发现的,私有(private)成员会像其他所有成员一样被继承。

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

关于c++ - 如何在派生类 C++ 中访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49469042/

相关文章:

c++ - C/C++ 中的跨平台线程/静态变量 fork

带有模板的 C++ Clang 优化错误

c++ - 使用 std::vector 时发生访问冲突

c++ - 使用鼠标手动提取对象

c++ - header 和 cpp 或仅 cpp 文件 - 最佳实践?

c++ - uint32_t 指针指向与 uint8_t 指针相同的位置

c++ - Eigen C++;就地矩阵乘法

c++ - ReadFile 没有正确读取字节

c++ - 在 C++17 中获取以毫秒为单位的时间?

c++ - 这是常见的优化吗?