首页 > 解决方案 > 为什么会这样编译?cout<"是";

问题描述

#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";
}

另外,我启用了编译器警告,但没有。

标签: c++gcc

解决方案


GCC<6.1(包括您的 4.9.2)中的默认 C++ 标准是gnu++98,而对于 GCC≥6.1 它是gnu++14(如此处所记录)。因此,后一种编译器默认不会接受此代码,因为explicit operator bool()它自 C++11 以来就存在于 iostreams 中,而不是operator void*()C++98 中(参见例如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";
}

推荐阅读