0

I want to create a constant static int variable to specify the range of an array. I'm running into problems and getting errors saying that the variable is not a member of the class, but I can print out the variable in main using ClassName::staticVarName.

I cannot figure out how to properly set up a static variable that belongs to a class so that it can be used to initialize an array. The variable prints in main, but for some reason it will not compile when I try to use it to define a classes's array field's range.

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

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

header file for class:

#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 file for class:

#include "RisingSunPuzzle.h"

const int RisingSunPuzzle::cols = 5;
const int RisingSunPuzzle::rows = 4;


RisingSunPuzzle::RisingSunPuzzle()
{
}


RisingSunPuzzle::~RisingSunPuzzle()
{
}

void RisingSunPuzzle::solvePuzzle()
{

}

void RisingSunPuzzle::clearboard()
{

}

1 Answer 1

4

The names of data members that are referred to must be declared before the data members that refer them to.

Also the static constants have to be initializes.

You can reformat the class the following way

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();
};

//...

There is no need to define the constants if they are not ODR used. Nevertheless you can define them (without initializers) like

    const int RisingSunPuzzle::cols;
    const int RisingSunPuzzle::rows;
1
  • Normally one doesn't add RisingSunPuzzle:: to scope rows and cols after private: as they are in scope.
    – doug
    Commented Dec 24, 2016 at 22:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.