C++使用 string 和 istream_iterator 的编译错误
当尝试编译以下内容时:
#include <string>
#include <iterator>
#include <iostream>
using namespace std;
int main() {
string s(istream_iterator<char>(cin), istream_iterator<char>());
return s.size();
}
g++ 4.4.1 给了我:
main.cc: In function ‘int main()’:
main.cc:6: error: request for member ‘size’ in ‘s’, which is of non-class type ‘std::string(std::istream_iterator<char, char, std::char_traits<char>, int>, std::istream_iterator<char, char, std::char_traits<char>, int> (*)())’
根据 libstdc++ 文档,字符串有一个接受开始/结束迭代器对的构造函数。那为什么我会收到这个错误呢?
When trying to compile the following:
#include <string>
#include <iterator>
#include <iostream>
using namespace std;
int main() {
string s(istream_iterator<char>(cin), istream_iterator<char>());
return s.size();
}
g++ 4.4.1 gives me:
main.cc: In function ‘int main()’:
main.cc:6: error: request for member ‘size’ in ‘s’, which is of non-class type ‘std::string(std::istream_iterator<char, char, std::char_traits<char>, int>, std::istream_iterator<char, char, std::char_traits<char>, int> (*)())’
According to libstdc++ docs, string has a ctor that takes a begin/end iterator pair. Why do I get this error, then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不小心声明了一个函数而不是实例化了一个字符串。尝试为 istream_iterator 对象声明变量,然后将它们传递给 std::string 构造函数。
这是一篇很好的文章,准确描述了您的问题: http://www.gotw.ca/gotw /075.htm
You're accidentally declaring a function instead of instantiating a string. Try declaring variables for your istream_iterator objects and then passing those to the std::string constructor.
And here's a good read that describes exactly your problem: http://www.gotw.ca/gotw/075.htm
搜索“最令人烦恼的解析”,你会发现比你想知道的更多的东西。
最重要的是,编译器将您的两个参数解释为指定类型而不是值。反过来,这会导致它将您的定义解释为函数的声明。
Search for "most vexing parse", and you'll find more than you want to know.
The bottom line is that the compiler is interpreting your two parameters as specifying types instead of values. That, in turn, leads it to interpret your definition as being a declaration of a function instead.
您声明了一个函数而不是变量。写入以下内容进行修复:
You've declared a function instead of variable. Write the following to fix: