C++实现多态的方式
时间: 2024-06-15 19:04:58 浏览: 16
C++实现多态的方式主要有以下几种:
1. 虚函数(Virtual Functions):通过在基类中声明虚函数,并在派生类中进行重写,实现多态性。当通过基类指针或引用调用虚函数时,会根据实际对象的类型来确定调用哪个函数。
2. 纯虚函数(Pure Virtual Functions):在基类中声明纯虚函数,即函数没有具体的实现,派生类必须重写该函数才能实例化对象。纯虚函数使得基类成为抽象类,只能被继承而不能被实例化。
3. 虚析构函数(Virtual Destructors):当基类指针指向派生类对象时,如果基类的析构函数不是虚函数,那么只会调用基类的析构函数,而不会调用派生类的析构函数。为了确保正确释放资源,需要将基类的析构函数声明为虚函数。
相关问题
c++实现多态的方式
C++实现多态的方式有两种:虚函数和模板。
1. 虚函数:在基类中声明虚函数,在派生类中重写该函数,通过基类指针或引用调用该函数时,会根据实际对象类型调用对应的函数。
示例代码:
```
class Animal {
public:
virtual void speak() {
cout << "Animal speaks!" << endl;
}
};
class Cat : public Animal {
public:
void speak() {
cout << "Cat meows!" << endl;
}
};
int main() {
Animal* animal = new Cat();
animal->speak(); // 输出 Cat meows!
delete animal;
return 0;
}
```
2. 模板:使用模板实现泛型编程,可以在编译时根据实际类型生成对应的代码。
示例代码:
```
template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int a = 1, b = 2;
swap(a, b); // a=2, b=1
return 0;
}
```
用C++实现 多态方式实例化子类对象并调用shout方法打印输出信息,要求如下
好的,以下是C++实现多态方式实例化子类对象并调用shout方法打印输出信息的示例代码:
```cpp
#include <iostream>
using namespace std;
class Animal {
public:
virtual void shout() {
cout << "Animal shouts!" << endl;
}
};
class Dog : public Animal {
public:
void shout() override {
cout << "Woof! Woof!" << endl;
}
};
class Cat : public Animal {
public:
void shout() override {
cout << "Meow! Meow!" << endl;
}
};
int main() {
Animal* animalPtr;
Dog dog;
Cat cat;
animalPtr = &dog;
animalPtr->shout(); // 调用 Dog 的 shout 方法
animalPtr = &cat;
animalPtr->shout(); // 调用 Cat 的 shout 方法
return 0;
}
```
在上述代码中,首先定义了一个抽象类 `Animal`,其中包含了一个虚函数 `shout()`。然后定义了两个子类 `Dog` 和 `Cat`,分别重写了 `shout()` 函数。
在 `main()` 函数中,首先定义了一个指向 `Animal` 类的指针 `animalPtr`,然后使用 `&` 运算符将 `dog` 和 `cat` 对象的地址分别赋值给 `animalPtr`。这样,就可以通过 `animalPtr` 调用 `shout()` 函数了。
由于 `shout()` 函数是虚函数,因此在调用时会根据对象的实际类型来确定调用哪个版本的 `shout()` 函数,从而实现了多态。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)