我看过很多关于这方面的帖子,但它们似乎都是在定义spme类方法时解决的。
app的背景:我只是想做一个基本的数独游戏来掌握C++的诀窍。
这个错误似乎与主函数.cpp文件无关,所以我将忽略它,除非它被要求保持解释简短。
board.h文件:
#pragma once
class board
{
public:
board(int gameSize, int diffifuclty) : gameSize(gameSize), difficulty(difficulty) {};
~board();
private:
int gameSize; int difficulty;
int game[gameSize][gameSize][gameSize][gameSize];
void createRandom(); // Creates a random workable board.
void hasSolution(); // Checks if there's a solution from the current state.
};
我还没有过多地使用board.cpp文件,因为我只是忙于定义board.h文件中的所有内容,以规划我想要编写的函数。
无论如何,我想要一个游戏板,在控制台上输入gameSize
和difficulty
。当我尝试为游戏板构造多维数组时,我得到了标题中提到的错误。(因此,对于数独,9x9游戏的游戏大小为3。)
我不确定错误是什么,或者如何使这个数组成为板级的属性(我不确定这是否是C++术语,很抱歉)?
发布于 2017-10-14 10:13:02
您遇到的问题是典型的C++ OOP问题。你可以找到更多的解释here。
这是因为在引用类的任何成员之前,您没有先创建对象。
例如,
construct(game); // game is a member of class board. you need to create an object of board first.
这是正确的
board bd;
construct(bd.game);
发布于 2021-12-06 16:31:57
在C++中的First中,数组的大小必须是编译时常量.So,例如以下代码片段:
int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression
编写上述代码的正确方法是:
const int n = 10;
int arr[n]; //CORRECT
同样,以下代码(您在代码示例中执行的操作)也是不正确的:
int gameSize; int difficulty;
int game[gameSize][gameSize][gameSize][gameSize];//INCORRECT because gameSize isn't a constant expression
解决方案
要解决此问题,您可以使用3D**std::vector
并使用构造函数初始化器列表对其进行初始化**,如下所示:
#pragma once
#include <vector>
class board
{
public:
//USE THE CONSTRUCTOR INITIALIZER LIST
board(int gameSize, int diffifuclty) : gameSize(gameSize),
difficulty(difficulty),
game(gameSize, std::vector<std::vector<int>>(gameSize, std::vector<int>(gameSize))) {};
~board();
private:
int gameSize; int difficulty;
//a 3D vector instead of built in array
std::vector<std::vector<std::vector<int>>> game;
void createRandom();
void hasSolution();
};
https://stackoverflow.com/questions/46740130
复制相似问题