1.隐藏的基本概念
什么是隐藏 ?就是说在下面的这种情况下,父类的ABC会在子类中进行隐藏,但是子类的确继承了父类的ABC函数 。如果一定要使用父类中的ABC,那么必须进行特殊处理。
(1)成员函数的隐藏
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Person{
public:
Person(){
name = "父类初始化" ;
}
void play() {
name = "由父类 Person 设置 " ;
cout << "Person 中的 play 函数 " << endl ;
}
protected:
string name ;
};
class Worker : public Person
{
public:
Worker() = default ;
void play(){
name = "由子类 Worker 设置 " ;
cout << "Worker 中的 play 函数 " << endl ;
}
void print(){
cout << "name == " << name << endl;
}
protected:
};
int main(void){
Worker work1 ;
work1.play() ;
work1.print();
cout << "--------------------------------------------------------"<< endl ;
work1.Person::play();
work1.print();
return 0 ;
}
运行结果:
值得一提的是:
- 如果父类与子类中的函数参数类型与个数不相同,也会发生隐藏现象,也就是说不会发生重载 。
- 必须使用这种写法去调用父类隐藏的成员函数“work1.Person::play(); ”
- 当然了,说了这麽多,又有谁会去这样去设计代码呐,切~
(2)数据成员变量的隐藏
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Person{
public:
Person(){
name = "父类初始化" ;
}
void Person_print() {
cout << "In Person_print name == " << name << endl;
}
protected:
string name ;
};
class Worker : public Person
{
public:
Worker() = default ;
void play_in_Worker(string Worker_str){
name = Worker_str ;
cout << "Worker 中的 play 函数 " << endl ;
}
void print(){
cout << "In Worker name == " << name << endl;
}
protected:
string name ;
};
int main(void){
Worker work1 ;
work1.play_in_Worker("liu") ;
work1.print();
work1.Person_print();
cout << "--------------------------------------------------------"<< endl ;
work1.play_in_Worker("sheng") ;
work1.print();
work1.Person_print();
return 0 ;
}
运行结果:
改进:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Person{
public:
Person(){
name = "父类初始化" ;
}
void Person_print() {
cout << "In Person_print name == " << name << endl;
}
protected:
string name ;
};
class Worker : public Person
{
public:
Worker() = default ;
void play_in_Worker(string Worker_str,string Person_str){
name = Worker_str ;
Person::name = Person_str ;
cout << "Worker 中的 play 函数 " << endl ;
}
void print(){
cout << "In Worker name == " << name << endl;
}
protected:
string name ;
};
int main(void){
Worker work1 ;
work1.play_in_Worker("liu","555") ;
work1.print();
work1.Person_print();
cout << "--------------------------------------------------------"<< endl ;
work1.play_in_Worker("sheng","666") ;
work1.print();
work1.Person_print();
return 0 ;
}
运行结果: