创建一个Monitor类,它能知道成员函数incident()被调用了几次. 增加一个成员函数print(),显示incident()被调用的次数, 并能在没有定义任何Monitor类的对象时,就显示次数的初始值 提示:使用静态成员(数据和函数)
时间: 2023-05-24 10:01:18 浏览: 116
以下是创建Monitor类的示例代码,它能够记录成员函数incident()被调用的次数,并能够在没有定义Monitor类的对象时,显示初始次数为0的情况。
```cpp
class Monitor {
private:
static int count; // 静态计数器,记录incident()函数被调用的次数
public:
static int getCount() { // 静态函数,用于获取incident()函数被调用的次数
return count;
}
static void resetCount() { // 静态函数,用于重置计数器的值
count = 0;
}
void incident() { // 成员函数,用于记录事件发生次数
count++;
}
void print() { // 成员函数,用于输出事件发生的次数
std::cout << "incident()函数被调用了 " << count << " 次!" << std::endl;
}
};
int Monitor::count = 0; // 初始化静态计数器的值为0
int main() {
Monitor::resetCount(); // 在没有定义任何Monitor类的对象时,重置计数器为0
Monitor m;
m.incident();
m.incident();
m.incident();
m.print(); // 输出事件发生的次数为3
std::cout << "初始事件发生次数为: " << Monitor::getCount() << std::endl; // 输出初始值0
return 0;
}
```
编写时需要注意的是,静态成员函数和静态变量都与类相关而不是具体的对象,因此可以在没有定义任何类对象的情况下使用它们。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)