【问题标题】:Typo: bool to int conversion induced error in std::ifstream under Linux错字:Linux 下 std::ifstream 中的 bool 到 int 转换导致错误
【发布时间】:2017-11-23 13:19:54
【问题描述】:

我有一个错字(|| 而不是|),并注意到这样的代码在 GCC 中失败并使用 Visual 进行编译。 我知道std::ifstream 的第二个参数是int。所以理论上,bool 必须隐式转换为int。那么为什么会失败呢?

引发错误的示例(我只是使用了一些整数而不是标志)。

#include <fstream>

int main(int argc, char * argv[]) {
  std::ifstream("foo", 2 | 3 || 4)
}

【问题讨论】:

    标签: c++ language-lawyer ifstream


    【解决方案1】:

    std::ifstream's constructorstd::ios_base::openmode 作为第二个参数,它是typedefed 来自实现定义 类型:

    typedef /*implementation defined*/ openmode;
    

    Visual 似乎使用整数,而 GCC 没有,这就是您的代码在 GCC 上失败的原因。

    【讨论】:

    • 谢谢你的答案。不管是什么原因,这对我来说似乎有点奇怪。标准库函数参数的类型是实现定义的可能是什么原因。它不会导致便携性问题吗?
    • @dgrat 你只应该使用明确定义的openmode
    • 我想知道我的问题的所有赞成票。预期相反,因为这似乎是一个初学者问题。
    • @dgrat when life give you lemons...我对你的问题投了赞成票,因为我不知道为什么你的代码适用于 MSVC 而不是 GCC,了解其中的原因很有趣。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2023-04-04
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多