【问题标题】:array was not declared in this scope数组未在此范围内声明
【发布时间】:2012-11-16 22:06:58
【问题描述】:

我编写了一个 c++ 程序,其中使用了 array 对象并包含 <array> 头文件,但是当我尝试使用 g++ 编译它时,它返回很多错误消息,说“数组未在这个范围”。它有什么问题。 程序在这里:

#include <iostream>
#include <string>
#include <array>

using namespace std;

const int Seasons = 4;
const array<string, Seasons> Snames =
 {"spring", "summer", "fall", "winter"};

void fill(array<double, Seasons>* pa);
void show(array<double, Seasons> da);

int main()
{
array<double, Seasons> expenses;
fill(&expenses);
show(expenses);

return 0;
}

void fill(array<double, Seasons>* pa)
{
 for(int i = 0; i < Seasons; i++)
 {
    cout << "Enter " << Snames[i] << " expenses: ";
    cin >> *pa[i];
 }
}

void show(array<double, Seasons> da)
{
double total = 0.0;
cout << "\nEXPENSES\n";

 for(int i = 0; i < Seasons; i++)
 {
    cout << Snames[i] << ": $" << da[i] << endl;
    total += da[i];
 }
cout << "Total Expenses: $" << total << endl;
}

【问题讨论】:

  • 命名空间呢?你在你的代码中叫它std::array 吗?更好的是,您能显示您的代码吗?
  • 我不知道!没人知道。你知道为什么?因为你没有显示你的代码。
  • 能否请您发布您的代码?
  • 请尝试编译以下VC++ 2012正确编译的代码:#include using namespace std; int main() { 数组 a;一[1] = 9;返回0; }
  • 您的代码应该更简洁以突出重点。

标签: c++ g++


【解决方案1】:

您的程序无法编译的最可能原因是 &lt;array&gt; 标头与 C11 之前的编译器不兼容。添加

-std=c++0x

到您的 g++ 的标志以启用 C++11 支持。一旦你这样做了,你会得到一个different error,因为第 28 行应该是

cin >> (*pa)[i];

已编辑;原始答案建议缺少对std:: 的引用)

【讨论】:

【解决方案2】:

它被称为 std::array - 它以 std:: 命名空间限定符为前缀,就像每个标准库类或函数 [模板]。

【讨论】:

    【解决方案3】:

    在#include 之后添加以下任一:

    using namespace std;
    using std::array;
    

    【讨论】:

    • 您在这里错过了该问题最重要的修复方法。
    • 你能说得具体点吗?
    • 你错过了写为什么这些行解决了问题,而array 是命名空间std 的成员,这是答案中最重要的部分。又名完全限定名称为std::array
    • Bleh,不会与那些无法区分语言新手和普通程序员的人争论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2016-08-09
    • 2019-02-17
    • 2021-01-07
    • 2016-10-27
    • 2016-06-03
    相关资源
    最近更新 更多