使用模板时出现奇怪错误< class InputIterator> string(InputIterator begin,InputIterator end); [英] Strange Error in using template<class InputIterator> string (InputIterator begin, InputIterator end);

查看:247
本文介绍了使用模板时出现奇怪错误< class InputIterator> string(InputIterator begin,InputIterator end);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这样的代码段:

#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从文件构造一个字符串。

The code constructs a string from a file using istream_iterator.

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

Notice that the first parameter of string constructor is enclosed with a pair of parentheses. If I omit the parentheses, there will be an error. In VC++ 2008, a link error will come about. In G++, the code has a wrong output.

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

I feel very strange about the parentheses. What's the difference and why?

推荐答案

没有额外括号,你得到C ++的最烦琐的解析用两个istream_iterators定义一个名为 str 的对象来指定它的初始化器,它被解析为一个名为 str 返回 string ,括号中的stuff指定它需要的参数类型。

Without the "extra" parentheses, you get C++'s "most vexing parse" -- instead of defining an object named str with the two istream_iterators to specify its initializers, it's parsed as a declaration of a function named str that returns a string, and the "stuff" in parentheses specifies the types of parameters it takes.

这篇关于使用模板时出现奇怪错误&lt; class InputIterator&gt; string(InputIterator begin,InputIterator end);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆