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

6qqygrtg  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(177)

此问题在此处已有答案

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

#ifndef REMAINDER_COUNTER_H
#define REMAINDER_COUNTER_H

extern int count;
int read();
int increment();
int decrement();

#endif //REMAINDER_COUNTER_H

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

int count;

int read(){
    return count;
}

int increment(){
    if (count < 5)
        count++;
    return count;
}

int decrement(){
    if (count > 0)
        count--;
    return count;
}


主文件名为“mainxc.cpp”:

#include <iostream>
#include "counter.h"

int main(){
    count = 2;
    for (int i = count; i <= 6; i+=2)
        increment();
    std::cout << read();
}


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

hfwmuf9z

hfwmuf9z1#

下面是一个类的例子:

#include <iostream>

// You have an invariant in your code 0 <= m_count <= 5
// in C++ that means : wrap it in a class (one of the main
// responsibility of classes is to safeguard invariants)

class counter_t
{
public:
    int increment()
    {
        if (m_count < 5) 
        {
            ++m_count;
        }

        return m_count;
    }

    int decrement()
    {
        if (m_count > 0) 
        {
            --m_count;
        }

        return m_count;
    }

    int get() // kind of convention to call readouts get (or get_count);
    {
        return m_count;
    }

private:
    int m_count{ 0 }; // Initializes m_count to 0
};

int main()
{
    counter_t counter;
    for(int n=0; n < 7; ++n) // convention is to use `<` instead of `<=`
    {
        counter.increment();
    }

    std::cout << counter.get();

    return 0;
}

字符串

相关问题