【问题标题】:Errors trying to declare array in class definition尝试在类定义中声明数组时出错
【发布时间】:2015-02-21 19:18:36
【问题描述】:

在过去的一个小时里,我一直试图让这个类拥有一个私有数组数据成员,但它拒绝工作。我不想用 数组[5] 地图数组; 因为那时我没有得到数组成员函数。

这是我目前正在使用的代码。

#include "stdafx.h"
#include <iostream>
#include <array>
#include <fstream>

class Map {
public:
    void scanFile();
private:
    size_t columns = 20;
    size_t rows = 20;
    array <int, 5> mapArray;
};



int main() {
    Map myMap;
}

以下是我在 Visual Studio 中遇到的一些示例错误。

1>x:\aerofs\gt\ece 2036\lab03\map.cpp(12): error C2143: syntax error : missing ';' before '<'
1>x:\aerofs\gt\ece 2036\lab03\map.cpp(12): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>x:\aerofs\gt\ece 2036\lab03\map.cpp(12): error C2238: unexpected token(s) preceding ';'

【问题讨论】:

  • array 类是在std 命名空间中定义的,所以试试std::array
  • 谢谢,我没有意识到这个名字实际上来自标准空间。

标签: c++ arrays class initialization


【解决方案1】:

你得到了编译错误。这是因为数组是在命名空间 std 中定义的。要么添加

using namespace std;

在文件顶部或在使用其中定义的任何类型之前添加std::

std::array< int, 5> mapArray;

后者是首选,因为您不必为了使用 array 类型而从标准库中引入所有符号。

【讨论】:

    【解决方案2】:

    标准 STL 类,包括 std::array,是 std:: 命名空间的一部分。

    因此,您只需将 std:: 命名空间限定符添加到您的 array 数据成员:

    std::array<int, 5> mapArray;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 2014-06-09
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多