非 POD 元素类型 'string'(又名 '<char>basic_string')c++ 的可变长度数组

Variable length array of non-POD element type 'string' (aka 'basic_string<char>') c++

本文关键字:string c++ 数组 char 类型 元素 POD 又名 gt lt basic      更新时间:2023-10-16

我在非POD元素类型string(又名basic_string<char>)的c++代码可变长度数组中收到此错误。

string words[numWords];

如果我去掉numWords并输入一个数字,这很好,但如果我把同一个数字放在一个变量中,就会出现Variable length array of non-POD element type 'string' (aka 'basic_string<char>')错误,我以前也这样做过,它在visualstudio中有效,但我现在在Xcode中尝试过,但它不起作用。我试过使用矢量,但我无法获得它们来存储任何数据,它们只是返回空白。

对于那些问这是我的矢量代码应该都在那里

char ch;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
while(repFile.get(ch))
{
    if(ch == ' ' || ch == 'n' || ch == 't')
    {
        numWords++;
    }
}
vector<string> words (numWords);
while(repFile >> x)
    words.push_back(x);
repFile.close();

C++没有C99风格的可变长度数组。您的编译器可能支持它们作为扩展,但它们不是语言的一部分。在这种特定的情况下,您在VisualStudio中的成功表明它实际上具有这样的扩展。clang++将支持VLA,但仅支持POD类型,因此您尝试创建string对象的VLA是行不通的。如果我省略了足够多的警告/错误标志,g++在我的机器上确实有效。

这用numWords空字符串初始化words,然后附加实际字符串:

vector<string> words (numWords);
while(repFile >> x)
    words.push_back(x);

更改为:

vector<string> words;
while(repFile >> x)
    words.push_back(x);

或:

vector<string> words (numWords);
int idx = 0;
while(repFile >> x /* && idx < numWords */)
    words[idx++] = x;

编辑:

在填充vector:之前,没有理由计算字数

vector<string> words;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
if (repFile.is_open())
{
    while(repFile >> x)
    {
        words.push_back(x);
    }
    repFile.close();
}

对不起,您需要编写gcc --version才能获得版本。

正如其他人所说,不应该使用可变长度数组,但GCC确实支持将它们作为C++中的扩展。我的GCC 4.4.4用以下代码编译得很好:

#include <string>
#include <iostream>
using namespace std;
int main() {
  int n;
  cin >> n;
  string s[n];
  return 0;
}

那个代码是为你编译的吗?如果是这样,那么您需要给我们一段最小的失败代码。

不过,最好的解决方案是使用vector<string>