纯虚函数的实现,举个例子
时间: 2024-05-11 10:16:15 浏览: 19
好的,关于纯虚函数的实现,我们可以举一个简单的例子。假设我们有一个基类Animal,其中有一个纯虚函数makeSound(),表示动物发出声音的操作。那么,派生类必须实现makeSound()函数才能被创建。
具体的代码实现如下:
```
class Animal {
public:
virtual void makeSound() = 0; // 纯虚函数
};
class Cat : public Animal {
public:
void makeSound() {
cout << "喵喵喵" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() {
cout << "汪汪汪" << endl;
}
};
```
在这个例子中,Animal类中的makeSound()函数被声明为纯虚函数,表示这个函数没有实现的具体内容。这时,我们创建子类Cat和Dog,并重写了父类中的makeSound()函数,为其添加了具体的实现。这样,我们就可以通过Cat和Dog类来创建实例了。
相关问题
纯虚函数怎么在派生类中实现举例子
在派生类中实现纯虚函数,需要重写该函数并提供实现。下面是一个简单的例子:
```
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double getArea() { return width * height; } // 实现纯虚函数
private:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double getArea() { return 3.14 * radius * radius; } // 实现纯虚函数
private:
double radius;
};
int main() {
Rectangle rect(3, 4);
Circle circle(5);
std::cout << "Rectangle area: " << rect.getArea() << std::endl;
std::cout << "Circle area: " << circle.getArea() << std::endl;
return 0;
}
```
在上面的代码中,`Shape` 类中定义了一个纯虚函数 `getArea()`,但是并没有提供实现。而 `Rectangle` 和 `Circle` 类都继承自 `Shape`,并在自己的类中实现了 `getArea()` 函数,从而提供了对应形状的面积计算方法。在 `main()` 函数中,我们分别创建了一个矩形和一个圆形对象,并输出它们的面积。
可以举一个纯虚函数的例子吗
当然可以,纯虚函数是在基类中声明的虚函数,但没有实现,需要在派生类中实现。例如:
```
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double getArea() {
return 3.14 * radius * radius;
}
private:
double radius;
};
```
在上面的例子中,Shape 类中的 getArea() 函数是纯虚函数,因为它没有实现。而 Circle 类继承了 Shape 类,并实现了 getArea() 函数,计算圆的面积。
相关推荐
![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)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)