首页 > 解决方案 > 非静态成员引用的二维数组问题

问题描述

我这里有一个代码,但是我不知道错误在哪里,也没有在网上找到任何有用的东西。

#ifndef TICTACTOE_H
#define TICTACTOE_H
#include <iostream>
#include <string>

class TicTacToe {
    public:
    int lines = 3;
    int columns = 3;
    std::string grid[lines][columns] = { { "#", "#", "#" }, { "#", "#", "#" }, { "#", "#", "#" } };
};


#endif

我在 [] 括号中的行和列中收到错误消息:

非静态成员引用必须相对于某个对象

我希望你能帮助我。

标签: c++

解决方案


编译器必须提前知道类的大小。由于lines并且columns可以为类的每个实例以不同方式初始化,因此它们不能用作数组的大小(否则类的大小将无法控制地改变)


如果您想坚持使用数组,可以将它们更改为const(expr) static成员。

class TicTacToe {
    public:
    constexpr static int lines = 3; 
    constexpr static int columns = 3;
    std::string grid[lines][columns] = { { "#", "#", "#" }, { "#", "#", "#" }, { "#", "#", "#" } };
};

现在linescolumns是不可变的(无法更改)并且对于每个TicTacToe类实例都是通用的。


如果你不想要常量值,你可以使用std::vector

class TicTacToe {
    public:
    std::vector<std::vector<std::string>> grid = { { "#", "#", "#" }, { "#", "#", "#" }, { "#", "#", "#" } };
};

std::vector可以随时调整大小。


推荐阅读