#include #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: 长毛

C++ 多态性示例:基类和派生类对象调用函数

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

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