简体   繁体   English

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

[英]Why does this compile? cout<"Yes";

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

it compiles, but when it runs, it does nothing.它可以编译,但是当它运行时,它什么也不做。 this is a compilation error elsewhere.这是其他地方的编译错误。 compiler is gcc 4.9.2编译器是 gcc 4.9.2

compared with和....相比

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

it has a missing '<' but it still compiles.它缺少一个“<”,但它仍然可以编译。

I expected it to be a compilation error, as with variables, like this:我预计它是一个编译错误,就像变量一样,如下所示:

> 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')

this happens with the code below as well.这也发生在下面的代码中。

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

edit: The same thing happens for编辑:同样的事情发生在

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

plus, I enabled compiler warnings and there are none.另外,我启用了编译器警告,但没有。

Default C++ standard in GCC<6.1 (which includes your 4.9.2) is gnu++98 , while for GCC≥6.1 it's gnu++14 (as documented eg here ). GCC<6.1(包括您的 4.9.2)中的默认 C++ 标准是gnu++98 ,而对于 GCC≥6.1,它是gnu++14 (如记录在此)。 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 eg cppreference ).因此,后者编译器默认不会接受此代码,因为自 C++11 以来,iostream 中存在explicit operator bool()而不是 C++98 中的operator void*() (参见例如cppreference )。

You could have been warned if you had turned on the warnings:如果您打开警告,您可能会收到警告:

$ 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";
               ^

where test.cpp contains example code:其中test.cpp包含示例代码:

#include <iostream>

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

Prior to C++11, the way that if (std::cin >> var) was supported was the stream objects having an implicit conversion to void * .在 C++11 之前,支持if (std::cin >> var)是将流对象隐式转换为void *

So std::cout<"Yes" is evaluated as calling the built in bool operator<(void*, const void*) , after applying the conversions std::basic_ios -> void * and const char[4] -> const char* -> const void* .因此std::cout<"Yes"在应用转换std::basic_ios -> void *const char[4] -> const char*之后被评估为调用内置bool operator<(void*, const void*) const char* -> const void*

Since C++11, there is now a rule that an explicit conversion to bool can be used in if , while etc. With that, the operator void* was changed to be explicit operator bool , and overload resolution correctly finds no match for std::cout<"Yes"从 C++11 开始,现在有一条规则,可以在ifwhile等中使用explicit转换为bool 。由此, operator void*更改为explicit operator bool ,并且重载解析正确地找不到std::cout<"Yes"匹配项std::cout<"Yes"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM