gpt4 book ai didi

c++ - vector 构造函数标识为函数

转载 作者:行者123 更新时间:2023-12-02 18:24:22 25 4
gpt4 key购买 nike

考虑这段代码:

#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <string>

int main() {
std::istringstream ss("abcabc abc a b e");
std::vector<std::string> words(std::istream_iterator<std::string>(ss), std::istream_iterator<std::string>());
std::string deciphered;
int shift = 5;
for (size_t i = 0; i < shift; i++)
{
for (size_t j = 0; i + j < words.size(); j += shift)
{
deciphered += words[i + j];
}
}
}

基本上,我想拆分单词并将它们存储到我的 words 中大批。但我遇到编译错误:

main.cpp: In function 'int main()':
main.cpp:14:40: error: request for member 'size' in 'words', which is of non-class type 'std::vector<std::__cxx11::basic_string<char> >(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)())'
14 | for (size_t j = 0; i + j < words.size(); j += shift)
| ^~~~
main.cpp:16:33: warning: pointer to a function used in arithmetic [-Wpointer-arith]
16 | deciphered += words[i + j];
| ^
main.cpp:16:33: error: invalid conversion from 'std::vector<std::__cxx11::basic_string<char> > (*)(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)())' to 'char' [-fpermissive]
16 | deciphered += words[i + j];
| ~~~~~~~~~~~^
| |
| std::vector<std::__cxx11::basic_string<char> > (*)(std::istream_iterator<std::__cxx11::basic_string<char> >, std::istream_iterator<std::__cxx11::basic_string<char> > (*)())
In file included from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\string:55,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\locale_classes.h:40,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\ios_base.h:41,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ios:42,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\ostream:38,
from c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\iostream:39,
from main.cpp:1:
c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\bits\basic_string.h:1186:25: note: initializing argument 1 of 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator+=(_CharT) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'
1186 | operator+=(_CharT __c)
| ~~~~~~~^~~

从错误来看,我的变量 words被识别为一个函数。

我很困惑,这种行为的原因是什么?我该如何解决它?

最佳答案

这就是所谓的 most vexing parse ,在这种情况下,您应该使用大括号初始化语法,这将使编译器知道您正在尝试构造类的实例而不是声明函数。

std::vector<int> a{}而不是std::vector<int> a()

关于c++ - vector 构造函数标识为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70426700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com