【问题标题】:2D Array Problems with non static member reference非静态成员引用的二维数组问题
【发布时间】:2020-04-06 10:02:22
【问题描述】:

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

#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++


    【解决方案1】:

    编译器必须提前知道类的大小。由于linescolumns 可以针对类的每个实例进行不同的初始化,因此它们不能用作数组的大小(否则类的大小会发生无法控制的变化)


    如果您想坚持使用数组,可以将它们更改为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 可以随时调整大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多