C++——继承(1) 隐藏
- 课前补充:
C++ 中放在public中的成员可以直接访问,如person
中的y
在main函数中可以直接访问
放在protected中不可以直接访问, 如cout << person.x << endl;//访问失败
但可以通过成员函数进行访问,如person.eat();
class Person
{
public:
Person();
~Person();
void eat(){
cout << x << endl;
}
int y;
protected:
int x;
};
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
Person person;
cout << person.y << endl;
person.eat();
//cout << person.x << endl;//访问失败
return 0;
}
隐藏
继承中的隐藏关键字:
隐藏:子类继承父类后,子类中有与父类同名的函数以及变量,则父类的函数及变量就会被隐藏,首先调用的是子类的函数或变量。
用子类名.父类名::函数();
调用被隐藏的函数或变量,
如cooler.Man::play();
cout << cooler.Man::age << endl;
头文件
#include <iostream>
#include "Cooler.h"
#include "Man.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
Cooler cooler;
cooler.play();
cooler.Man::play();
//cout << cooler.Man::age << endl;
return 0;
}
class Man
{
public:
Man();
void play();
int age;
protected:
};
cpp文件:
Man :: Man(){
age = 20;
}
void Man :: play(){
age = 20;
cout << "Man-play()" << endl;
}
class Cooler : public Man
{
public:
void play();
int age;
protected:
};
cpp文件:
void Cooler :: play(){
age = 10;
cout << "Coolerplay()" << endl;
cout << age << endl;
cout << Man :: age << endl;
}