c++继承时名字遮蔽问题

#include<iostream>
#include<cstdlib>
using namespace std;
//基类people
class People
{
public:
    void show();
protected:
   const char* m_name;
    int m_age;
};
void People::show()
{
    cout << "嗨,大家好!我叫" << m_name << ",今年" << m_age << "" << endl;

}
//派生类Student
class Student :public People
{
public:
    Student(const char* name, int age, float score);
    void show();//遮蔽基类的show()
private:
    float m_score;
};
Student::Student(const char* name, int age, float score)
{
    m_name = name;
    m_age = age;
    m_score = score;
}
void Student::show()
{
    cout << m_name << "的年龄是" << m_age << ",成绩是" << m_score << endl;

}
int main()
{
    Student stu("小明", 16, 55.5);
    //使用派生类新增的成员函数,而不是从基类继承的
    stu.show();
    //使用的是从基类继承来的成员函数
    stu.People::show();
    system("pause");
    return 0;
}

如果派生类中的成员(包括成员变量和成员函数)和基类中的成员重名,那么就会遮蔽从基类继承过来的成员。所谓遮蔽,就是在派生类中使用该成员(包括在定义派生类时使用,也包括通过派生类对象访问该成员)时,实际上使用的是派生类新增的成员,而不是从基类继承来的。

调用的时候,加上类名和域解析符

stu.People::show();

猜你喜欢

转载自www.cnblogs.com/qq1480040000/p/12950854.html
今日推荐