【问题标题】:Why does this compile? cout<"Yes";为什么会这样编译? cout<"是";
【发布时间】:2021-12-17 17:32:36
【问题描述】:
#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";
}

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

【问题讨论】:

  • 你的意思是写cout &lt;&lt; "Yes";
  • 有很多拼写错误导致语法正确。
  • GCC 4.9.2 已经过时了,你可能会尝试一个更新的——尽管想知道为什么 std::ostream 和指针有一个 less 运算符(如果它编译,如你所说)......跨度>
  • 为什么这个问题被关闭了?在 C++11 之前,basic_ios 有 operator void*() 所以 cout 被强制转换为指针,然后
  • 如果您将文本作为文本而不是链接或图像发布,我会考虑投票重新开放。

标签: c++ gcc


【解决方案1】:

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

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

从 C++11 开始,现在有一个规则,即 explicit 转换为 bool 可以在 ifwhile 等中使用。因此,operator void* 更改为 @987654336 @,并且重载解析正确地找不到 std::cout&lt;"Yes" 的匹配项

【讨论】:

  • 我想补充一点,即使使用 -std=c++11 -pedantic (Compiler Explorer),g++ 4.9.2 也能接受这个损坏的代码。它可能太老了,无法正确处理。
  • void*, char const* 运营商?不是void*, void*吗?
  • @Scheff'sCat 4.8 与 5.5(我在本地拥有的版本)的一个区别是前者无条件地定义了 basic_ios::operator void*(),而后者只为 __cplusplus &lt; 201103L 定义了它。我想 4.8 在这方面与 4.9 没有太大区别。
【解决方案2】:

GCCgnu++98,而对于 GCC≥6.1,它是 gnu++14(如文档所述,例如 here)。因此,后一种编译器默认不接受此代码,因为自 C++11 以来 iostreams 中存在 explicit operator bool() 而不是 C++98 中的 operator void*()(参见例如 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";
}

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 2022-07-06
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多