帮我写一份C++多肽的代码
以下是一个简单的C++多态示例:
#include <iostream>
using namespace std;
// 基类
class Animal {
public:
virtual void sound() {
cout << "这是一个动物。" << endl;
}
};
// 派生类
class Cat : public Animal {
public:
void sound() {
cout << "喵喵喵。" << endl;
}
};
// 派生类
class Dog : public Animal {
public:
void sound() {
cout << "汪汪汪。" << endl;
}
};
// 派生类
class Bird : public Animal {
public:
void sound() {
cout << "啾啾啾。" << endl;
}
};
int main() {
Animal* animal1 = new Cat();
Animal* animal2 = new Dog();
Animal* animal3 = new Bird();
animal1->sound();
animal2->sound();
animal3->sound();
delete animal1;
delete animal2;
delete animal3;
return 0;
}
该程序定义了一个动物基类,以及三个派生类:猫,狗和鸟。每个派生类都重写了基类的 sound() 方法,以便在调用时输出相应的声音。在 main() 函数中,创建了三个 Animal 类型的指针,分别指向派生类的实例。在调用它们的 sound() 方法时,将根据实际类型调用相应的重写方法。最后,删除动态分配的内存以避免内存泄漏。
原文地址: https://www.cveoy.top/t/topic/biMs 著作权归作者所有。请勿转载和采集!