关于C++中的布尔值的问题
Question about bool in C++
我想知道为什么下面的代码只返回"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;
}
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 变量定义到C++布尔值转换
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 重载更少,则运算符返回相反的布尔值
- 将此布尔值传递给此函数的最有效方法是什么?
- 如何设置 c++ 类的布尔值?
- 使用 MAKEWORD / MAKEWPARAM 使用布尔值而不是布尔值
- 将 10 个线程与原子布尔值同步
- 创建类似于布尔值的变量类型
- 布尔值向量的基于范围 for 循环
- 零点和布尔值之间的比较
- 简化对两个布尔值的 4 个 if/else 检查
- 无法创建带有布尔值和矢量的地图
- 对于完成布尔值设置为 true 后未停止的循环
- fstream / ifstream / ofstream 对象如何转换为布尔值
- C++:将值赋值给原始数据类型(例如布尔值)是原子操作吗?
- 关于如何在 cout 中处理布尔值的考试问题
- 在结束取决于布尔值的 do/while 循环时遇到问题 - C++
- 布尔值返回两次有问题(Arduino)
- 关于C++中的布尔值的问题