c++ - 使用模板 <class InputIterator> string (InputIterator begin, InputIterator end) 时出现奇怪的错误;

标签 c++ stl iterator stdstring istream-iterator

给定这样一个代码段:

#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
using namespace std;
int main(){
    ifstream file("1.txt");
    string str((istream_iterator<char>(file)),istream_iterator<char>());
    file.close();
    cout<<str<<endl;
}

代码使用 istream_iterator 从文件构造字符串。

请注意,字符串构造函数的第一个参数是用一对括号括起来的。如果我省略了括号,就会出现错误。在 VC++ 2008 中,会出现链接错误。在 G++ 中,代码输出错误。

感觉括号很奇怪。有什么区别,为什么?

最佳答案

如果没有“额外的”括号,您将得到 C++ 的“最令人烦恼的解析”——而不是定义一个名为 str 的对象并使用两个 istream_iterator 来指定其初始化器,它被解析为一个声明名为 str 的函数返回一个 string,括号中的“stuff”指定它采用的参数类型。

关于c++ - 使用模板 <class InputIterator> string (InputIterator begin, InputIterator end) 时出现奇怪的错误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10039657/

相关文章:

c++ - 在游戏中显示帧的最快方法

c++ - STL 容器中的 Const 函数

c++ - C++ 代码可以在 C++03 和 C++11 中都有效但做不同的事情吗?

c++ - STL背后的设计原理

c++ - 合并来自 std::set 的相邻条目

c++ - 具有链接时代码生成的 MSVC 能否跨 C 和 C++ 进行优化?

c++ - 在C++中模拟虚拟构造函数

c++ - insert_iterator 失效规则

arrays - 如何在iter的位置方法中访问索引?

c++ - 在 C++ 中使用集合迭代器