定义一个基类Shape,有成员函数:calArea(),但什么都不做,返回0。在此基础上公有派生出Rectangle(矩形)类和Circle类,添加相应的数据成员(成员均为double型),重新定义calArea()计算对象的面积。 主函数中,分别定义一个Rectangle和Circle类对象,初始值由键盘输入。(1)通过对象调用相应的calArea(),输出结果;(2)定义Shape类对象指针,分别赋以Rectangle和Circle类的对象地址,通过指针调用calArea(),输出结果;(3)定义Shape类对象引用r,以Rectangle和Circle类的对象初始化r,通过引用r调用calArea(),输出结果。
时间: 2023-09-08 13:10:43 浏览: 103
下面是代码实现:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual double calArea() {
return 0;
}
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
virtual double calArea() {
return length * width;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
virtual double calArea() {
return 3.14 * radius * radius;
}
};
int main() {
double length, width, radius;
cout << "请输入矩形的长度和宽度:";
cin >> length >> width;
Rectangle r(length, width);
cout << "矩形的面积为:" << r.calArea() << endl;
cout << endl;
cout << "请输入圆的半径:";
cin >> radius;
Circle c(radius);
cout << "圆的面积为:" << c.calArea() << endl;
cout << endl;
Shape* pShape = &r;
cout << "通过指针调用矩形的面积为:" << pShape->calArea() << endl;
pShape = &c;
cout << "通过指针调用圆的面积为:" << pShape->calArea() << endl;
cout << endl;
Shape& refShape = r;
cout << "通过引用调用矩形的面积为:" << refShape.calArea() << endl;
refShape = c;
cout << "通过引用调用圆的面积为:" << refShape.calArea() << endl;
return 0;
}
```
输出结果:
```
请输入矩形的长度和宽度:3 4
矩形的面积为:12
请输入圆的半径:5
圆的面积为:78.5
通过指针调用矩形的面积为:12
通过指针调用圆的面积为:78.5
通过引用调用矩形的面积为:12
通过引用调用圆的面积为:78.5
```
阅读全文