(1) 下面是一个计数器类的定义,请完成该类的实现,并在 main( )函数中演示该类 的应用。 class counter{ int value; public: counter(int number); void increment(); //给原值加 1 void decrement(); //给原值减 1 int getvalue(); //取得计数器的值 void print(); //显示计数器的值 };
时间: 2023-06-01 13:07:53 浏览: 72
好的,以下是我对您提出的问题的回答。
(1) 以下是一个计数器类的定义,请完成该类的实现,并在 main( )函数中演示该类 的应用。
class counter{
int value;
public:
counter(int number);
void increment(); //给原值加 1
void decrement(); //给原值减 1
int getvalue(); //取得计数器的值
void print(); //显示计数器的值
};
counter::counter(int number){
value = number;
}
void counter::increment(){
value++;
}
void counter::decrement(){
value--;
}
int counter::getvalue(){
return value;
}
void counter::print(){
cout << "当前计数器的值为:" << value << endl;
}
int main(){
counter cnt(0); //初始化计数器为0
cnt.print(); //输出计数器的初始值
cnt.increment(); //对计数器加1
cnt.print(); //输出计数器的新值
cnt.decrement(); //对计数器减1
cnt.print(); //输出计数器的新值
return 0;
}
以上是计数器类的简单实现,您可以在main函数中创建对象并演示该类的使用。请注意,在increment和decrement函数中,我们对类成员变量value进行加1或减1的操作,最后通过getvalue函数取得计数器的值,并在print函数中输出。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)