设置一个求面积的虚函数Area
时间: 2024-03-20 12:43:04 浏览: 17
好的,我理解你的要求了。下面是一个简单的示例代码,展示如何在C++中设置一个虚函数Area用于计算面积:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual float Area() = 0; // 纯虚函数
};
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) {
radius = r;
}
float Area() {
return 3.14 * radius * radius;
}
};
class Rectangle : public Shape {
private:
float length;
float breadth;
public:
Rectangle(float l, float b) {
length = l;
breadth = b;
}
float Area() {
return length * breadth;
}
};
int main() {
Shape *shape; // 基类指针
Circle c(5);
Rectangle r(4, 6);
shape = &c;
cout << "Area of circle: " << shape->Area() << endl;
shape = &r;
cout << "Area of rectangle: " << shape->Area() << endl;
return 0;
}
```
在上面的代码中,我们定义了一个抽象基类Shape,其中有一个纯虚函数Area。然后我们定义了两个派生类Circle和Rectangle,分别计算圆和矩形的面积。在main函数中,我们通过基类指针访问派生类对象的Area函数,实现了多态性。