#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class person {
private: char name[50];
int age;
public: void get_name() {
cout<<"Enter name"<<endl;
gets(name);
}
void put_name() {
cout<<"Name : ";
puts(name);
cout<<endl;
}
void get_age() {
cout<<"Enter age"<<endl;
cin>>age;
}
void put_age() {
cout<<"Age : "<<age<<endl;
}
};
class student : public person {
private : int roll;
public : void get_roll() {
cout<<"Enter roll"<<endl;
cin>>roll;
}
void put_roll() {
cout<<"Roll : "<<roll<<endl;
}
};
int main() {
student A;
A.get_name();
A.get_roll();
A.get_age();
A.put_name();
A.put_age();
A.put_roll();
getch();
clrscr();
return 0;
}
有以下查询:
- 如果
person
类的私有(private)成员没有在student
类中继承,那么student
类的实例如何在其中存储值? - 难道变量不应该存在于类
student
中吗?
注意:我在大学项目中使用旧编译器。
最佳答案
如果一个 Student 想要访问 Person 字段,最简单的方法是将它们设置为protected,这样它们就可以被 Person 的所有派生类访问。
另一种方法是使用公共(public) getter/setter 方法(你甚至可以将它们设置为 protected ,但此时最好使用 protected 字段),这样所有类都可以看到和设置 Person 的字段。< br/>
事实上,即使一个变量在基类中被声明为 private,它也存在于派生类中(一个 Student 在任何情况下都是一个 Person,所以 Person 中的字段必须被初始化)但是它不能'她联系不上。
关于c++ - C++中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46945684/