2011-05-19 55 views
0

我想知道为什么下面的代码只返回“测试”四次而不是五次?关于Bool在C++中的问题

#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 << "test\n"; 
    } 
+2

您是否缺少''end'方法中的'return'? – sje397 2011-05-19 05:57:17

+0

你能发布'end'方法的正确定义吗? – Naveen 2011-05-19 05:57:56

+1

我也有点困惑,'CountDown i = 5'这句话不应该起作用。不应该是'CountDown * i = new CountDown(5)'或者'CountDown i(5)' – 2011-05-19 06:21:46

回答

4

有在做这个双初始化没有一点:

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

这是不够的:

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

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

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

至于结束()你不'从它返回任何值。该方法应该看起来像这样:

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

更改end()函数使其仅输出“test”一次... – mikhailovich 2011-05-19 06:12:08

+1

真的吗?因为当我测试它时,它会打印测试5次 – 2011-05-19 06:21:36

+0

这是另一个错误,对不起,你是对的。 – mikhailovich 2011-05-19 06:30:59

0

试试这个。

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

不必要的混淆:'it> 1'具有'bool'类型,可以直接输出(或否定,但我宁愿反转测试:'it <= 0')。当然,价值是错误的,正如你写的那样,它应该是'it> 0'。 – 2011-05-19 07:50:38