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

问题描述:

我想创建一个常量静态int变量来指定数组的范围。我遇到了问题,并得到错误说变量不是该类的成员,但我可以使用ClassName :: staticVarName打印出主变量。尝试使用它初始化数组时,未标识C++ const静态成员

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

error: class "RisingSunPuzzle" has no member "rows"

error: class "RisingSunPuzzle" has no member "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; 
+0

定义它们(不初始化)正常情况下一个不经过''私人:: RisingSunPuzzle'添加范围行和cols:'因为他们在范围之内。 – doug