c++ 当使用全局变量调用3次时,我的函数increment不会打印6 [duplicate]

6qqygrtg  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(203)

此问题在此处已有答案

What is a debugger and how can it help me diagnose problems?(2个答案)
5天前关闭。
我有一个标题叫做“counter. h”:

  1. #ifndef REMAINDER_COUNTER_H
  2. #define REMAINDER_COUNTER_H
  3. extern int count;
  4. int read();
  5. int increment();
  6. int decrement();
  7. #endif //REMAINDER_COUNTER_H

字符串
名为counter.cpp的c++文件:

  1. int count;
  2. int read(){
  3. return count;
  4. }
  5. int increment(){
  6. if (count < 5)
  7. count++;
  8. return count;
  9. }
  10. int decrement(){
  11. if (count > 0)
  12. count--;
  13. return count;
  14. }


主文件名为“mainxc.cpp”:

  1. #include <iostream>
  2. #include "counter.h"
  3. int main(){
  4. count = 2;
  5. for (int i = count; i <= 6; i+=2)
  6. increment();
  7. std::cout << read();
  8. }


我尝试只使用函数read()3次就得到6,但它不打印6,而是打印5。为什么?

hfwmuf9z

hfwmuf9z1#

下面是一个类的例子:

  1. #include <iostream>
  2. // You have an invariant in your code 0 <= m_count <= 5
  3. // in C++ that means : wrap it in a class (one of the main
  4. // responsibility of classes is to safeguard invariants)
  5. class counter_t
  6. {
  7. public:
  8. int increment()
  9. {
  10. if (m_count < 5)
  11. {
  12. ++m_count;
  13. }
  14. return m_count;
  15. }
  16. int decrement()
  17. {
  18. if (m_count > 0)
  19. {
  20. --m_count;
  21. }
  22. return m_count;
  23. }
  24. int get() // kind of convention to call readouts get (or get_count);
  25. {
  26. return m_count;
  27. }
  28. private:
  29. int m_count{ 0 }; // Initializes m_count to 0
  30. };
  31. int main()
  32. {
  33. counter_t counter;
  34. for(int n=0; n < 7; ++n) // convention is to use `<` instead of `<=`
  35. {
  36. counter.increment();
  37. }
  38. std::cout << counter.get();
  39. return 0;
  40. }

字符串

展开查看全部

相关问题