【发布时间】: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++