dan*_*doh 0 c++ for-loop operator-overloading
我在C++中有这个程序有一个简单的for循环,for循环没有检查条件:
for (std::string a_word; std::cin >> a_word;) {
// code goes here
}
// Code after the loop
Run Code Online (Sandbox Code Playgroud)
我编译它们并在终端上运行,当我按下Ctrl + D(EOF)时,for循环然后停止并在循环后运行代码,虽然没有检查条件,有人可以解释引擎盖下发生了什么吗?
你误会了.循环中有一个条件
for (std::string a_word; std::cin >> a_word;) {
^^^^^^^^^^^^^^^^^^
// code goes here
}
Run Code Online (Sandbox Code Playgroud)
它是
std::cin >> a_word;
Run Code Online (Sandbox Code Playgroud)
for语句的这一部分中的任何表达式(或声明)都在上下文中转换为type bool.
来自C++标准(6.4选择语句)
- ...作为表达式的条件的值是表达式的值,对于除switch之外的语句,上下文转换为bool ;
在C++ Standatrd中为流定义了显式运算符
explicit operator bool() const;
Run Code Online (Sandbox Code Playgroud)
返回!fail().
表达式std::cin >> a_word;返回引用,std::cin并应用上面显示的转换运算符.
所以当你按下Ctrl + D然后fail()返回true并且loop(!fail())的条件等于false.