【问题标题】:Variable length array of non-POD element type 'string' (aka 'basic_string<char>') c++非POD元素类型'string'(又名'basic_string<char>')的可变长度数组c ++
【发布时间】:2012-03-21 23:37:19
【问题描述】:

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

string words[numWords];

如果我摆脱 numWords 并输入一个数字,这很好,但如果我将相同的数字放在一个变量中,它会给我 Variable length array of non-POD element type 'string' (aka 'basic_string&lt;char&gt;') 错误,我以前这样做过,它在 Visual Studio 中工作,但我现在已经在 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();

【问题讨论】:

  • 这与 Xcode 无关。它与您使用的编译器有关。我认为某些版本的 gcc? gcc -version 说什么?
  • 你能发布你的vector代码吗?
  • 对数组大小使用变量是不标准的。使用 vector 应该可以工作,所以真正的问题是找出为什么它不适合你。
  • gcc -version 说没有输入文件。
  • Variable length arrays in C++? 的可能重复项

标签: c++ arrays xcode string xcode4


【解决方案1】:

C++ 没有 C99 风格的可变长度数组。您的编译器可能支持它们作为扩展,但它们不是语言的一部分。在这种特定情况下,您使用 Visual Studio 取得的成功表明它确实具有这样的扩展。 clang++ 将支持 VLA,但仅支持 POD 类型,因此您尝试制作 string 对象的 VLA 将不起作用。如果我留下足够多的警告/错误标志,g++ 确实可以在我的机器上工作。

【讨论】:

  • 或者它可能只是动态值用于初始化 const int 并且 VS 未能发现该值不是静态产生的,以便发出警告/错误。我已经看到它发生了。
  • 可能是。我对 Visual Studio 几乎一无所知。
  • 我也在 GCC 中看到过。远比意外使用扩展程序更有可能,IMO。
【解决方案2】:

这会使用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();
}

【讨论】:

  • 我已经尝试了你的两种解决方案,但一个抛出异常,另一个仍然什么也没打印,认为这可能是我的电脑或愚蠢的错误
  • 我认为您需要在第二个 while 之前重新打开 repFile
  • 谢谢你得到它我不得不关闭repFile然后再次打开它感谢大家的所有帮助。
  • 为什么你的代码示例中有额外的副本。 while(repFile &gt;&gt; words[idx++]) {}
  • @LokiAstari,监督。谢谢。
【解决方案3】:

抱歉,您需要写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&lt;string&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2013-06-30
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多