【问题标题】:C++ const static member is not identified when trying to use it to initialize an array尝试使用 C++ const 静态成员初始化数组时未识别它
【发布时间】:2016-12-24 18:06:08
【问题描述】:

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

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

错误:“RisingSunPuzzle”类没有成员“行”

错误:“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()
{

}

【问题讨论】:

    标签: c++ arrays static initialization member


    【解决方案1】:

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

    还必须初始化静态常量。

    您可以通过以下方式重新格式化类

    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;
    

    【讨论】:

    • 通常不会将RisingSunPuzzle:: 添加到private: 之后的范围行和列中,因为它们在范围内。
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    相关资源
    最近更新 更多