C++使用 string 和 istream_iterator 的编译错误

发布于 2024-08-10 02:37:02 字数 760 浏览 4 评论 0原文

当尝试编译以下内容时:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感性不性感 2024-08-17 02:37:02

您不小心声明了一个函数而不是实例化了一个字符串。尝试为 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

素食主义者 2024-08-17 02:37:02

搜索“最令人烦恼的解析”,你会发现比你想知道的更多的东西。

最重要的是,编译器将您的两个参数解释为指定类型而不是值。反过来,这会导致它将您的定义解释为函数的声明。

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.

掐死时间 2024-08-17 02:37:02

您声明了一个函数而不是变量。写入以下内容进行修复:

string s(istream_iterator<char>(cin), (istream_iterator<char>()));

You've declared a function instead of variable. Write the following to fix:

string s(istream_iterator<char>(cin), (istream_iterator<char>()));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文