试图在类定义中声明数组时出错

Errors trying to declare array in class definition

本文关键字:声明 数组 出错 定义      更新时间:2023-10-16

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

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

#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;
}

下面是我在VisualStudio中遇到的一些错误示例。

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

您出现编译错误。这是因为数组是在命名空间std中定义的。请添加

using namespace std;

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

std::array< int, 5> mapArray;

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

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

因此,您可以简单地将std::名称空间限定符添加到array数据成员中:

std::array<int, 5> mapArray;