声明一个基类shapes,其中含有protected类型的数据成员x,y和r,它们分别代表矩形的长、宽及圆的半径值。
时间: 2023-06-02 22:01:49 浏览: 63
以下为C++代码实现:
```
class shapes {
protected:
int x; // 矩形的长
int y; // 矩形的宽
int r; // 圆的半径值
};
```
相关问题
声明一个基类shapes,其中含有protected类型的数据成员x,y和r,它们分别代表矩形的长、宽及圆的半径值。成员函数insquare()用来设置数据成员x,y的初值,成员函数incircle()用来设置数据成员r的初值;定义show_area()为纯虚函数;声明类square及circle为shapes的派生类,其成员函数show_area()分别用来计算矩形和圆的面积。))))
class shapes{
protected:
double x, y, r;
public:
void insquare(double a, double b){
x = a;
y = b;
}
void incircle(double c){
r = c;
}
virtual void show_area() = 0;
};
class square: public shapes{
public:
void show_area(){
double area = x * y;
cout << "The area of the square is: " << area << endl;
}
};
class circle: public shapes{
public:
void show_area(){
double area = 3.14 * r * r;
cout << "The area of the circle is: " << area << endl;
}
};
声明一个基类Shape(形状),其中包含一个方法来计算面积; 从Shape 派生两个类:Rectangle(矩形类)和Circle(圆形类); 从Rectangle 类派生正方形类Square; 分别实现派生类构造函数、析构函数及其它功能的成员函数; 创建各派生类的对象,观察构造函数、析构函数的调用次序; 计算不同对象的面积。
好的,这是一个经典的面向对象编程问题。以下是一个C++的示例代码:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() {
return 0.0;
}
};
class Rectangle : public Shape {
protected:
double width, height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
cout << "Rectangle constructed" << endl;
}
~Rectangle() {
cout << "Rectangle destructed" << endl;
}
double area() {
return width * height;
}
};
class Square : public Rectangle {
public:
Square(double w) : Rectangle(w, w) {
cout << "Square constructed" << endl;
}
~Square() {
cout << "Square destructed" << endl;
}
};
class Circle : public Shape {
protected:
double radius;
public:
Circle(double r) {
radius = r;
cout << "Circle constructed" << endl;
}
~Circle() {
cout << "Circle destructed" << endl;
}
double area() {
return 3.14 * radius * radius;
}
};
int main() {
Shape* shapes[3];
shapes[0] = new Rectangle(2, 3);
shapes[1] = new Circle(4);
shapes[2] = new Square(5);
for (int i = 0; i < 3; i++) {
cout << "Area of shape " << i << " is " << shapes[i]->area() << endl;
delete shapes[i];
}
return 0;
}
```
运行结果如下:
```
Rectangle constructed
Circle constructed
Rectangle constructed
Square constructed
Area of shape 0 is 6
Rectangle destructed
Area of shape 1 is 50.24
Circle destructed
Area of shape 2 is 25
Square destructed
Rectangle destructed
```
在这个示例代码中,我们定义了一个基类Shape,其中包含一个虚函数area(),用来计算面积。然后我们从Shape派生出两个类Rectangle和Circle,分别代表矩形和圆形。从Rectangle又派生出Square,代表正方形。每个类都有自己的构造函数和析构函数,用于初始化对象和在对象被销毁时释放资源。在主函数中,我们创建了三个Shape类型的指针,分别指向了一个Rectangle、一个Circle和一个Square对象。然后我们遍历指针数组,输出每个对象的面积,并逐个删除它们。输出结果显示了对象的创建和销毁顺序,以及它们的面积。