使用C++的虚函数完成一段代码示例
时间: 2023-10-13 08:06:45 浏览: 35
抽象类:
```
class Animal {
public:
virtual void speak() = 0; // 纯虚函数
};
```
派生类:
```
class Dog : public Animal {
public:
void speak() {
cout << "汪汪汪" << endl;
}
};
class Cat : public Animal {
public:
void speak() {
cout << "喵喵喵" << endl;
}
};
```
使用:
```
int main() {
Animal *a1 = new Dog();
Animal *a2 = new Cat();
a1->speak();
a2->speak();
delete a1;
delete a2;
return 0;
}
```
相关问题
写一段C++的虚函数代码
以下是一个简单的C++虚函数的示例代码:
```c++
#include <iostream>
class Shape {
public:
virtual void draw() {
std::cout << "Shape::draw()" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() override {
std::cout << "Circle::draw()" << std::endl;
}
};
int main() {
Shape* shape = new Circle();
shape->draw();
delete shape;
return 0;
}
```
这段代码定义了两个类:Shape和Circle。Shape是一个基类,它有一个虚函数draw(),该函数在子类中进行重写。Circle是Shape的一个子类,它重写了draw()函数以实现绘制圆形的功能。
在main函数中,我们创建了一个指向Circle对象的Shape指针,然后调用了draw()函数。由于draw()是虚函数,因此程序会调用Circle类中的draw()函数而不是Shape类中的draw()函数。
输出结果为:
```
Circle::draw()
```
c++ 利用多态写一段代码
以下是一个简单的C++多态示例:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
// 调用 Rectangle 的 area 函数
shape->area();
shape = &tri;
// 调用 Triangle 的 area 函数
shape->area();
return 0;
}
```
输出:
```
Rectangle class area :
Triangle class area :
```
在这个示例中,我们定义了一个基类 `Shape`,并派生出两个子类 `Rectangle` 和 `Triangle`。在基类中,我们定义了一个虚函数 `area()`,并在每个子类中重写了它。在 `main()` 函数中,我们声明了一个指向 `Shape` 的指针 `shape`,并将其分别指向 `Rectangle` 和 `Triangle` 对象。然后我们调用 `shape` 的 `area()` 函数,由于 `area()` 是虚函数,程序会根据实际指向的对象类型来调用正确的函数,这就是多态的体现。