C++ 继承与派生---函数重载

C++ 继承与派生---函数重载

接上一篇基础的继承关系,这一篇为一个最简单的重载父类函数decription

传送门:https://shihoumao.com/post/8.html

子类Human.h增加函数定义

string description();

Human.cpp实现

/************************************************************************/
/*函数重载  重载父类的decription
//__super::description() 调用父的方法*  __super可用来访问父类方法
*/
/************************************************************************/
string Human::description()
{
    stringstream rct;
    rct<<__super::description()<<" 性别: "<<(sex==MAN?"男":"女");
    return  rct.str();
}


main.cpp修改

#include "Human.h"
int main(){                     
    Human zhangsan("张三",100,MAN);
    Animal fatherClass("动物",0);

    cout<<fatherClass.description()<<endl;
    //子类Human  在没有重载description之前  调用的是父类的方法。
    //cout<<zhangsan.description()<<" 性别: "<<(sex==MAN?"男":"女")<<endl;
    //重载后  调用子类自己的方法description
    //先查找子类方法,如果子类方法不存在,找父类的方法,还是没有找到则结束,失败。
    cout<<zhangsan.description()<<endl;

    system("pause");
    return 0;
}

运行结果与前一篇相同:

动物  weight: 0

张三  weight: 100 性别: 男