c++继承之隐藏

隐藏

概念:

隐藏是指派生类的函数屏蔽了与其同名的基类函数。

代码实例:

#include <iostream>
using namespace std;
class Person
{
public:
    Person(){
        cout<<"Person的构造函数"<<endl;
    }
    ~Person(){
        cout<<"Person的析构函数"<<endl;
    }
    void eat(){
        cout<<"Person的eat函数"<<endl;
    }
private:
    int m_iAge;
    string m_strName;
};
class Worker :public Person
{
public:
    Worker(){
        cout<<"Worker的构造函数"<<endl;
    }
    ~Worker(){
        cout<<"Worker的析构函数"<<endl;
    }
    void eat(){
        cout<<"Worker的eat函数"<<endl;
    }
    void work(){
        cout<<"Worker的work函数"<<endl;
    }
private:
    int m_iSalary;
};
int main()
{
    Worker w;
    w.eat();
    w.Person::eat();
    return 0;
}

运行结果为:

Person的构造函数
Worker的构造函数
Worker的eat函数
Person的eat函数
Worker的析构函数
Person的析构函数

--------------------------------
Process exited after 0.1206 seconds with return value 0
请按任意键继续. . .

简易解释

  • Worker是子类,Person是父类,我们在栈上实例化子类方法,首先调用父类构造函数,其次调用子类构造函数。析构函数则反之,并且栈上的空间是由系统管理,系统调用析构函数。
  • 父类中的eat()函数被隐藏,w.eat()调用的是子类的eat()函数。
  • 如果我们需要调用父类的成员函数,可以采用w.Person::eat();的方法。

几个易混淆的名词

  • 隐藏:
    不解释了
  • 覆盖或者称之为重写(override)
    如果我们没有在子类中定义同名的虚函数,那么在子类虚函数表当中就会写上父类当中那个虚函数的函数入口地址,如果我们在子类中也定义了同名的虚函数,那么在子类的虚函数表当中,我们就会把原来父类的虚函数的函数地址覆盖一下,覆盖成子类的虚函数的函数地址。
  • 如何记忆
    隐藏并没有消失,可以通过特殊的手段访问,数据成员也有隐藏这种现象。而覆盖则是在子类的虚函数表当中,我们就会把原来父类的虚函数的函数地址覆盖一下,覆盖成子类的虚函数的函数地址。(后续会有博客详细解释)

猜你喜欢

转载自blog.csdn.net/Jamence/article/details/81432908
今日推荐