当尝试使用它来初始化数组时,未识别C const静态成员

C++ const static member is not identified when trying to use it to initialize an array

本文关键字:识别 静态成员 const 数组 初始化      更新时间:2023-10-16

我想创建一个常数静态int变量来指定数组的范围。我遇到问题并遇到错误,说该变量不是类的成员,但是我可以使用className :: staticvarname在main中打印出变量。

我无法弄清楚如何正确设置属于类的静态变量,以便可以将其用于初始化数组。变量打印在MAIN中,但由于某种原因,当我尝试使用它来定义类的数组范围时,它不会编译。

错误:class'risingsunpuzzle'没有成员"行"

错误:class'risingsunpuzzle'没有成员" cols"

类的标题文件:

#pragma once
#include<map>
#include<string>
#include<memory>

class RisingSunPuzzle
{
private:
    bool board[RisingSunPuzzle::rows][RisingSunPuzzle::cols];   
public:
    RisingSunPuzzle();
    ~RisingSunPuzzle();
    static const int cols;
    static const int rows;
    void solvePuzzle();
    void clearboard();
};

cpp文件:

#include "RisingSunPuzzle.h"
const int RisingSunPuzzle::cols = 5;
const int RisingSunPuzzle::rows = 4;

RisingSunPuzzle::RisingSunPuzzle()
{
}

RisingSunPuzzle::~RisingSunPuzzle()
{
}
void RisingSunPuzzle::solvePuzzle()
{
}
void RisingSunPuzzle::clearboard()
{
}

必须在将其推荐给它们的数据成员之前声明所引用的数据成员的名称。

还必须初始化静态常数。

您可以按照以下方式重新格式化

class RisingSunPuzzle
{
public:
    static const int cols = 5;
    static const int rows = 4;
private:
    bool board[RisingSunPuzzle::rows][RisingSunPuzzle::cols];   
public:
    RisingSunPuzzle();
    ~RisingSunPuzzle();
    void solvePuzzle();
    void clearboard();
};

//...

如果不使用ODR,则无需定义常数。但是,您可以定义它们(没有初始化),例如

    const int RisingSunPuzzle::cols;
    const int RisingSunPuzzle::rows;