C++ 关于C+中bool的问题+;
我想知道为什么下面的代码只返回“Test”四次,而不是五次C++ 关于C+中bool的问题+;,c++,C++,我想知道为什么下面的代码只返回“Test”四次,而不是五次 #include <iostream> #include <cassert> using namespace std; class CountDown { public: //Application Programmer Interface CountDown(int start); // it is set to start
#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";
}
#包括
#包括
使用名称空间std;
班级倒计时
{
公共应用程序编程接口
倒计时(int start);//设置为开始
void next();//从中减去一
bool end()常量//
私人:
内特;
};
倒计时::倒计时(整数开始)
{
它=0;
它=开始;
}
void倒计时::next()
{
it=it-1;
}
布尔倒计时::end()常量
{
如果(它试试这个
bool CountDown::end() const
{
if (it > 1) return false;
return true;
}
试试这个
bool CountDown::end() const
{
if (it > 1) return false;
return true;
}
执行此双重初始化没有任何意义:
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倒计时::end()常量
{
返回它执行此双重初始化没有意义:
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倒计时::end()常量
{
return它您是否缺少end
方法中的return
?您能否发布end
方法的正确定义。我也有点困惑,“倒计时I=5”语句不应该起作用。它不应该是“倒计时*I=new CountDown(5)”还是“倒计时I(5)”呢“@Robert:倒计时i=5
有效;非显式构造函数允许从整数进行隐式转换。如果构造函数是显式的,则它必须是倒计时i(5)
正如你所说。当自动存储可以工作时,你不应该使用new
,特别是在这样的情况下,在使用后没有合理的方法删除对象。你是否缺少end
方法中的返回
?你能给出end
方法的正确定义吗?我也有点困惑,t语句“倒计时i=5”不应该工作。它不应该是“倒计时*i=new CountDown(5)”还是仅仅是“倒计时i(5)”@Robert:CountDown i=5
是有效的;非显式构造函数允许从整数隐式转换。如果构造函数是显式的,那么它必须是CountDown i(5)
正如你所说。当自动存储可以工作时,你不应该使用new
,特别是在这样的情况下,使用后没有合理的方法删除对象。真的吗?因为当我测试它时,它会打印测试5次真的吗?因为当我测试它时,它会打印测试5次不必要的混淆:it>1
具有类型bool
,可以直接输出(或否定,但我更愿意反向测试:它不必要的混淆:it>1
具有类型bool
,可以直接输出(或否定,但我更愿意反向测试:it