(3)统计平行四边形构造函数被调用的次数
时间: 2024-03-17 17:46:16 浏览: 11
如果你想统计平行四边形构造函数被调用的次数,可以在构造函数中定义一个静态变量来记录调用次数,每次调用构造函数时,将静态变量加 1。示例代码如下:
```cpp
class Parallelogram {
public:
Parallelogram(double width, double height)
: width_(width), height_(height) {
count_++; // 每次调用构造函数时,将 count_ 加 1
}
static int getCount() { return count_; } // 静态函数返回 count_ 的值
private:
double width_;
double height_;
static int count_; // 静态成员变量记录调用次数
};
int Parallelogram::count_ = 0; // 静态成员变量初始化为 0
int main() {
Parallelogram p1(2, 3);
Parallelogram p2(4, 5);
Parallelogram p3(6, 7);
cout << "Parallelogram count: " << Parallelogram::getCount() << endl; // 输出调用次数
return 0;
}
```
上述代码中,静态成员变量 `count_` 记录调用次数,在构造函数中将其加 1。静态函数 `getCount()` 返回调用次数。在 `main()` 函数中创建了 3 个平行四边形对象,最后输出调用次数。