定义四个类:定义平行四边形类Parallelogram,定义矩形类Rectangle,定义菱形类Diamond,定义正方形类Square;按照矩形、菱形继承平行四边形,正方形继承矩形、菱形的关系实现以下功能:1.实现类的继承与派生,创建正方形类的对象。2.实现调用平行四边形、矩形、菱形和正方形的showRes()函数。3.统计平行四边形构造函数被调用的次数。4.用C++实现。
时间: 2024-03-18 14:41:23 浏览: 146
以下是C++代码实现:
```cpp
#include <iostream>
using namespace std;
class Parallelogram {
public:
Parallelogram() {
count++;
}
void showRes() {
cout << "This is a parallelogram." << endl;
}
static int count;
};
class Rectangle : public Parallelogram {
public:
void showRes() {
cout << "This is a rectangle." << endl;
}
};
class Diamond : public Parallelogram {
public:
void showRes() {
cout << "This is a diamond." << endl;
}
};
class Square : public Rectangle, public Diamond {
public:
void showRes() {
cout << "This is a square." << endl;
}
};
int Parallelogram::count = 0;
int main() {
Square s;
s.showRes();
Rectangle r;
r.showRes();
Diamond d;
d.showRes();
Parallelogram p;
p.showRes();
cout << "The parallelogram constructor has been called " << Parallelogram::count << " times." << endl;
return 0;
}
```
输出结果为:
```
This is a square.
This is a rectangle.
This is a diamond.
This is a parallelogram.
The parallelogram constructor has been called 4 times.
```
解释:
1. 我们创建了一个正方形类对象s,并调用了其showRes()函数,输出"This is a square."。
2. 我们创建了一个矩形类对象r,并调用了其showRes()函数,输出"This is a rectangle."。
3. 我们创建了一个菱形类对象d,并调用了其showRes()函数,输出"This is a diamond."。
4. 我们创建了一个平行四边形类对象p,并调用了其showRes()函数,输出"This is a parallelogram."。
5. 最后输出平行四边形类构造函数被调用的次数,即4次。
阅读全文