为什么要编译? cout<"Yes";

Why does this compile? cout<"Yes";

#include<iostream>
using namespace std;
int main(){
     cout<"Yes"; 
}

它编译,但当它运行时,它什么都不做。这是其他地方的编译错误。 编译器是 gcc 4.9.2

相比
 #include<iostream>
    using namespace std;
    int main(){
         cout<<"Yes"; 
    }

它缺少一个“<”,但它仍然可以编译。

我预计这是一个编译错误,就像变量一样:

> 6 6   C:\Users\Denny\Desktop\Codes\compileerror.cpp   [Error] no match for
> 'operator<' (operand types are 'std::ostream {aka
> std::basic_ostream<char>}' and 'int')

下面的代码也会出现这种情况。

   #include<iostream>
    using namespace std;
    int main(){
         cin>"Yes"; 
    }

编辑: 同样的事情发生在

#include<iostream>
int main(){
    
    std::cout<"Yes";
}

此外,我启用了编译器警告并且有 none.

GCC<6.1(包括您的 4.9.2)中的默认 C++ 标准是 gnu++98,而对于 GCC≥6.1,它是 gnu++14(记录在案,例如 here). Thus the latter compiler won't accept this code by default, due to explicit operator bool() being present in the iostreams since C++11 instead of operator void*() in C++98 (see e.g. cppreference)。

如果您打开了警告,您可能会收到警告:

$ g++-4.8 test.cpp -o test -Wall
test.cpp: In function ‘int main()’:
test.cpp:5:15: warning: value computed is not used [-Wunused-value]
     std::cout < "Yes";
               ^

其中 test.cpp 包含示例代码:

#include <iostream>

int main()
{
    std::cout < "Yes";
}

在 C++11 之前,支持 if (std::cin >> var) 的方式是将流对象隐式转换为 void *

所以 std::cout<"Yes" 在应用转换 std::basic_ios -> void *const char[4] -> [= 后被评估为调用内置 bool operator<(void*, const void*) 17=] -> const void*.

从 C++11 开始,现在有一条规则,即 explicitbool 的转换可以在 ifwhile 等中使用。这样, operator void* 已更改为 explicit operator bool,并且重载解析正确地找到了 std::cout<"Yes"

的不匹配项