【问题标题】:C++: a nonstatic member reference must be relative to a specific objectC++:非静态成员引用必须相对于特定对象
【发布时间】:2018-03-26 04:37:51
【问题描述】:

我看过很多关于此的帖子,但它们似乎都是在定义 spme 类型的方法时解决的。

应用背景:只是想制作一个基本的数独游戏来掌握 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 文件中的所有内容以计划我要编写的函数。

无论如何,我想在控制台中输入gameSizedifficulty 的游戏板。当我尝试为游戏板构建多维数组时,我收到了标题中提到的错误。 (所以对于数独,9x9 游戏的游戏大小为 3。)

我不确定错误是什么或如何使这个数组成为板的属性(我不确定这是否是 C++ 术语,很抱歉)?

【问题讨论】:

  • 您的数组不能使用成员变量作为大小。它们必须在编译时可用。因此,要么使用 vector>>> 或使用带有翻译函数的 gamesize^4 向量,使用 int**** 或将其作为模板参数传递。

标签: c++ arrays error-handling compiler-errors member


【解决方案1】:

您遇到的问题是 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);

【讨论】:

  • 好吧,这就是我感到困惑的地方,因为我猜 C++ 在这方面与其他语言不同。首先,此代码是否进入我的main、board.h 文件或 board.cpp 文件?其次,我如何在课堂上根据需要制作多维数组?在其他语言中,做类似的事情不会给我带来问题,因为我只是使用一个属性。那么这里有什么不同呢?
  • 据我所知,Java、C# 等对static 有相同的概念。 C++ 与它们没有什么不同。通常 board.cpp 是类板的实现。板类的实例化在其他地方完成。
【解决方案2】:

首先在C++中,数组的大小必须是编译时常数。所以,以下面的代码sn-ps为例:

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

解决方案

要解决这个问题,您可以使用 3Dstd::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(); 

};

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 2016-08-13
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2018-10-23
    相关资源
    最近更新 更多