举个例子
时间: 2023-08-12 12:18:59 浏览: 40
好的,举个例子来说明虚函数的作用。
假设有一个基类Animal,它有一个虚函数eat(),然后有两个派生类Dog和Cat,它们都重载了eat()函数。代码如下:
```c++
class Animal {
public:
virtual void eat() {
cout << "Animal eats" << endl;
}
};
class Dog : public Animal {
public:
void eat() {
cout << "Dog eats bone" << endl;
}
};
class Cat : public Animal {
public:
void eat() {
cout << "Cat eats fish" << endl;
}
};
```
现在我们可以通过指向基类的指针来实现多态性,如下所示:
```c++
Animal *animal;
Dog dog;
Cat cat;
animal = &dog;
animal->eat(); // 输出 Dog eats bone
animal = &cat;
animal->eat(); // 输出 Cat eats fish
```
可以看到,尽管使用的是同一个基类指针,但是通过虚函数的机制,程序能够在运行时确定调用的是哪个子类函数,从而实现多态性。
相关问题
举个例子吧
好的,我来举个例子。比如说,我们要创建一个柱状图,其中x轴表示不同的城市名称,y轴表示每个城市的人口数量。为了使得图表更加美观,我们可以设置padding属性来调整图表的内边距。具体的代码如下:
```javascript
option = {
xAxis: {
type: 'category',
data: ['北京', '上海', '广州', '深圳', '杭州'],
axisLabel: {
interval: 0,
rotate: 30
}
},
yAxis: {
type: 'value'
},
series: [{
data: [2154, 2424, 1350, 1033, 981],
type: 'bar'
}],
grid: {
left: '5%',
right: '5%',
bottom: '5%',
top: '15%',
containLabel: true
},
padding: [10, 20, 10, 20]
};
```
在这个例子中,我们通过设置padding为[10, 20, 10, 20],即上、右、下、左四个方向的内边距分别为10、20、10、20像素,使得图表绘制区域与整个图表容器之间保留了一定的间距,使得图表更加美观。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)