c++ - 非静态成员引用的二维数组问题
问题描述
我这里有一个代码,但是我不知道错误在哪里,也没有在网上找到任何有用的东西。
#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
我在 [] 括号中的行和列中收到错误消息:
非静态成员引用必须相对于某个对象
我希望你能帮助我。
解决方案
编译器必须提前知道类的大小。由于lines
并且columns
可以为类的每个实例以不同方式初始化,因此它们不能用作数组的大小(否则类的大小将无法控制地改变)
如果您想坚持使用数组,可以将它们更改为const(expr) static
成员。
class TicTacToe {
public:
constexpr static int lines = 3;
constexpr static int columns = 3;
std::string grid[lines][columns] = { { "#", "#", "#" }, { "#", "#", "#" }, { "#", "#", "#" } };
};
现在lines
和columns
是不可变的(无法更改)并且对于每个TicTacToe
类实例都是通用的。
如果你不想要常量值,你可以使用std::vector
class TicTacToe {
public:
std::vector<std::vector<std::string>> grid = { { "#", "#", "#" }, { "#", "#", "#" }, { "#", "#", "#" } };
};
std::vector
可以随时调整大小。
推荐阅读
- google-geocoding-api - 谷歌地图 iframe 包含地址不显示部分匹配地图
- javascript - Alexa:无法将复数单词更改为单数
- talend - Talend 环境设置?
- ms-access - MS Access - 表单显示为空白(使用充当查询参数的列表框)
- batch-file - Dir 命令无法按我的意愿工作
- python - 我没有收到错误,但我似乎无法让 UDF 在 xlwings 中工作
- c# - 在 Visual Studio MCV 中使用 C# 从 Sage 300 ERP 中提取 Quantity on Hand 数据始终返回 0
- postgresql - Postgres CROSS JOIN JSON_TO_RECORD, JSON_EACH
- php - Laravel 和 MS SQL Server 数据库连接抛出错误“(3/3) QueryException 找不到驱动程序”
- visual-studio - 更改主帐户别名后,如何连接到我的 Teamproject?