C++学习16 继承时的名字遮蔽

时间:2023-03-09 23:07:41
C++学习16 继承时的名字遮蔽

如果派生类中的成员变量和基类中的成员变量重名,那么就会遮蔽从基类继承过来的成员变量。所谓遮蔽,就是使用新增的成员变量,而不使用继承来的。

成员函数也一样,如果函数名和参数签名都相同,就会造成遮蔽。如果仅仅是函数名相同,而参数签名不同,那么会构成重载。

请看下面的例子:

#include<iostream>
using namespace std;
class People{
protected:
char *name;
int age;
public:
void display();
};
void People::display(){
cout<<"嗨,大家好,我叫"<<name<<",今年"<<age<<"岁!"<<endl;
}
class Student: public People{
private:
float score;
public:
Student(char*, int, float);
void display(); //遮蔽从基类继承的display()
};
Student::Student(char *name, int age, float score){
this->name = name;
this->age = age;
this->score = score;
}
void Student::display(){
cout<<name<<"的年龄是"<<age<<",成绩是"<<score<<endl;
}
int main(){
Student stu("小明", , 90.5);
//使用的是派生类新增的函数,而不是从基类继承的
stu.display();
//使用的是从基类继承来的函数
stu.People::display();
return ;
}

本例中,基类 People 和派生类 Student 都定义了 display() 函数,会造成遮蔽,stu 是 Student 类的对象,默认使用 Student 类的 display(),如第34行代码所示。

但是,基类 People 中的 display() 函数仍然可以访问,不过要加上类名和域解析符,如第36行代码所示。