#include #include using namespace std;

class Animal { protected: int legs; string temperature; public: Animal(int l, string t) : legs(l), temperature(t) {} void display() { cout << "This animal has " << legs << " legs and is " << temperature << endl; } };

class Mammal : public Animal { protected: string hair; public: Mammal(int l, string t, string h) : Animal(l, t), hair(h) {} void display() { cout << "This mammal has " << legs << " legs and is " << temperature << " with " << hair << " hair" << endl; } };

void fun1(Animal* a) { a->display(); }

void fun2(Mammal* m) { m->display(); }

int main() { Animal a(4, "variable temperature"); Mammal m(4, "constant temperature", "short hair");

fun1(&a); // sends address of base class object a
fun1(&m); // sends address of derived class object m (upcasting)

fun2(&m); // sends address of derived class object m
fun2((Mammal*)&a); // sends address of base class object a, cast to derived class (downcasting)
// note: downcasting is not safe and should be done with caution
return 0;
C++程序:基类Animal含有数据成员legs腿数、string temperature恒温变温及成员函数 display 显示信息。 派生类Mammal含有 string hair长毛短毛无毛及成员函数display 显示信息。‎类外定义函数 fun1 以基类指针为形参内调用display‎类外定义函数fun2 以派生类指针为形参内调用display‎ ‎主函数定义 基类对象 a 和派生类对象

原文地址: http://www.cveoy.top/t/topic/fc08 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录