基类Animal含有数据成员legs腿数、string temperature恒温变温及成员函数 display 显示信息。 派生类Mammal含有 string hair长毛短毛无毛及成员函数display 显示信息。类外定义函数 fun1 以基类指针为形参内调用display类外定义函数fun2 以派生类指针为形参内调用display 主函数定义 基类对象 a 和派生类对象m 调用fu
可能会出现在调用fun2时,传入基类对象a的地址而不是派生类对象m的地址,因为基类对象没有hair属性,调用派生类的display函数时会出错。
以下是完整代码:
#include
using namespace std;
class Animal { protected: int legs; string temperature; public: Animal(int l, string t) : legs(l), temperature(t) {} virtual void display() { cout << "legs: " << legs << endl; cout << "temperature: " << temperature << endl; } };
class Mammal : public Animal { private: string hair; public: Mammal(int l, string t, string h) : Animal(l, t), hair(h) {} void display() override { Animal::display(); cout << "hair: " << hair << endl; } };
void fun1(Animal* a) { a->display(); }
void fun2(Mammal* m) { m->display(); }
int main() { Animal a(4, "恒温"); Mammal m(4, "恒温", "长毛");
fun1(&a);
fun1(&m);
//fun2(&a); //错误,基类对象没有hair属性
fun2(&m);
return 0;
}
运行截图:
legs: 4 temperature: 恒温 legs: 4 temperature: 恒温 hair: 长
原文地址: https://www.cveoy.top/t/topic/flTP 著作权归作者所有。请勿转载和采集!