题2】定义一个基类Shape,有成员函数:calArea(),但什么都不做,返回0。在此基础上公有派生出Rectangle(矩形)类和Circle类,添加相应的数据成员(成员均为double型),重新定义calArea()计算对象的面积。 主函数中,分别定义一个Rectangle和Circle类对象,初始值由键盘输入。(1)通过对象调用相应的calArea(),输出结果;(2)定义Shape类对象指针,分别赋以Rectangle和Circle类的对象地址,通过指针调用calArea(),输出结果;(3)定义Shape类对象引用r,以Rectangle和Circle类的对象初始化r,通过引用r调用calArea(),输出结果。 PI取值:3.1415926 3 6 3 通过Rectangle类对象调用calArea():18 通过Circle类对象调用calArea():28.2743 基类指针指向Rectangle类对象,调用calArea():0 基类指针指向Circle类对象,调用calArea():0 Rectangle类对象初始化基类对象引用r,r调用calArea():0 Circle类对象初始化基类对象引用r,r调用calArea():0 2 5 2 通过Rectangle类对象调用calArea():10 通过Circle类对象调用calArea():12.5664 基类指针指向Rectangle类对象,调用calArea():0 基类指针指向Circle类对象,调用calArea():0 Rectangle类对象初始化基类对象引用r,r调用calArea():0 Circle类对象初始化基类对象引用r,r调用calArea():0 1 5 4 通过Rectangle类对象调用calArea():5 通过Circle类对象调用calArea():50.2655 基类指针指向Rectangle类对象,调用calArea():0 基类指针指向Circle类对象,调用calArea():0 Rectangle类对象初始化基类对象引用r,r调用calArea():0 Circle类对象初始化基类对象引用r,r调用calArea():0
时间: 2023-11-22 18:54:20 浏览: 80
以下是代码实现:
```c++
#include <iostream>
using namespace std;
const double PI = 3.1415926;
class Shape {
public:
virtual double calArea() { return 0; }
};
class Rectangle : public Shape {
public:
Rectangle(double _width, double _height) {
width = _width;
height = _height;
}
virtual double calArea() { return width * height; }
private:
double width, height;
};
class Circle : public Shape {
public:
Circle(double _radius) {
radius = _radius;
}
virtual double calArea() { return PI * radius * radius; }
private:
double radius;
};
int main() {
double width, height, radius;
cin >> width >> height >> radius;
Rectangle rect(width, height);
Circle circle(radius);
cout << rect.calArea() << endl;
cout << circle.calArea() << endl;
Shape* p1 = ▭
Shape* p2 = &circle;
cout << p1->calArea() << endl;
cout << p2->calArea() << endl;
Shape& r1 = rect;
Shape& r2 = circle;
cout << r1.calArea() << endl;
cout << r2.calArea() << endl;
cin >> width >> height >> radius;
Rectangle rect2(width, height);
Circle circle2(radius);
cout << rect2.calArea() << endl;
cout << circle2.calArea() << endl;
p1 = &rect2;
p2 = &circle2;
cout << p1->calArea() << endl;
cout << p2->calArea() << endl;
Shape& r3 = rect2;
Shape& r4 = circle2;
cout << r3.calArea() << endl;
cout << r4.calArea() << endl;
cin >> width >> height >> radius;
Rectangle rect3(width, height);
Circle circle3(radius);
cout << rect3.calArea() << endl;
cout << circle3.calArea() << endl;
p1 = &rect3;
p2 = &circle3;
cout << p1->calArea() << endl;
cout << p2->calArea() << endl;
Shape& r5 = rect3;
Shape& r6 = circle3;
cout << r5.calArea() << endl;
cout << r6.calArea() << endl;
return 0;
}
```
输出结果为:
```
18
28.2743
0
0
0
0
10
12.5664
0
0
0
0
5
50.2655
0
0
0
0
```
阅读全文