请问虚函数有几种使用方法举例子谢谢
时间: 2023-09-27 21:06:20 浏览: 54
虚函数主要有以下两种使用方法:
1. 在基类中声明虚函数,派生类中重写该函数:
```c++
class Animal {
public:
virtual void makeSound() {
cout << "This is the sound of an animal." << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "Woof! Woof!" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() {
cout << "Meow! Meow!" << endl;
}
};
int main() {
Animal* animal = new Animal();
animal->makeSound();
animal = new Dog();
animal->makeSound();
animal = new Cat();
animal->makeSound();
return 0;
}
```
输出结果为:
```
This is the sound of an animal.
Woof! Woof!
Meow! Meow!
```
2. 在基类中声明虚析构函数,派生类中重写该函数:
```c++
class Shape {
public:
virtual ~Shape() {
cout << "Shape destructor called." << endl;
}
virtual double getArea() = 0;
};
class Rectangle : public Shape {
public:
~Rectangle() {
cout << "Rectangle destructor called." << endl;
}
double getArea() {
return width * height;
}
private:
double width;
double height;
};
class Circle : public Shape {
public:
~Circle() {
cout << "Circle destructor called." << endl;
}
double getArea() {
return PI * radius * radius;
}
private:
double radius;
const double PI = 3.14159;
};
int main() {
Shape* shape = new Rectangle();
delete shape;
shape = new Circle();
delete shape;
return 0;
}
```
输出结果为:
```
Rectangle destructor called.
Shape destructor called.
Circle destructor called.
Shape destructor called.
```
相关推荐
![](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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)