pta 多态方式实例化子类对象并调用shout方法打印输出信息
时间: 2024-01-29 09:04:51 浏览: 54
假设有一个父类 Animal 和两个子类 Dog 和 Cat,并且它们都有一个共同的方法 shout(),可以通过以下多态方式实例化子类对象并调用shout方法打印输出信息:
```C++
#include <iostream>
using namespace std;
class Animal {
public:
virtual void shout() {
cout << "Animal shout!" << endl;
}
};
class Dog: public Animal {
public:
void shout() {
cout << "Dog shout: Woof woof!" << endl;
}
};
class Cat: public Animal {
public:
void shout() {
cout << "Cat shout: Meow meow!" << endl;
}
};
int main() {
Animal *a1 = new Dog();
a1->shout();
Animal *a2 = new Cat();
a2->shout();
return 0;
}
```
在上述代码中,Animal 类中的 shout() 方法被定义为虚函数,这样就可以在子类中重写该方法。在 main 函数中,使用 Animal 指针分别指向 Dog 和 Cat 类的实例化对象,然后调用它们的 shout() 方法,最终会输出以下信息:
```
Dog shout: Woof woof!
Cat shout: Meow meow!
```