关于C++中的布尔值的问题

Question about bool in C++

本文关键字:布尔值 问题 C++ 关于      更新时间:2023-10-16

我想知道为什么下面的代码只返回"Test"四次,而不是五次?

    #include <iostream>
    #include <cassert>
    using namespace std;
    class CountDown
    {
      public: //Application Programmer Interface
        CountDown(int start); // it is set to start
        void next(); // subtracts one from it
        bool end()const; //
     private:
        int it;
    };
    CountDown::CountDown(int start)
    {
        it = 0;
        it = start;
    }
    void CountDown::next()
    {
        it = it - 1;
    }
    bool CountDown::end() const
    {
        if (it <= 0)
          cout << "The countdown is now over" << endl;
    }
    int main()
    {
        for( CountDown i = 5 ; ! i.end(); i.next())
        std::cerr << "testn";
    }

执行此双重初始化是没有意义的:

CountDown::CountDown(int start)
{
    it = 0;
    it = start;
}

这就足够了:

CountDown::CountDown(int start)
{
    it = start;
}

甚至这样,使用初始化列表:

CountDown::CountDown(int start):it(start)
{
}

至于 end(),你不会从中返回任何值。该方法可能如下所示:

bool CountDown::end() const
{
    return it <= 0;
}

试试这个。

bool CountDown::end() const
  {
   if (it > 1) return false;
   return true;
  }