Reference Loop C++

  c++, constants, reference

I have a class Color, I want to define a constant of such class, and use that constant within the class. So the code may look like this:

class Color;

const Color BLACK = *new Color(0, 0, 0);
const Color WHITE = *new Color(255, 255, 255);

class Color {
    const int r;
    const int g;
    const int b;

    Color CloserBlackOrWhite() {
        int rgb = r + g + b;
        return rgb > (255*3/2) ? BLACK : WHITE;
    }
}

Of course, the issue with this is that BLACK/WHITE can’t be defined because they’re using an incomplete-type. I tried fixing this by placing the consts below the class decloration.

class Color {
    const int r;
    const int g;
    const int b;

    Color CloserBlackOrWhite() {
        int rgb = r + g + b;
        return rgb > (255*3/2) ? BLACK : WHITE;
    }
}

const Color BLACK = *new Color(0, 0, 0);
const Color WHITE = *new Color(255, 255, 255);

Except now in CloserBlackOrWhite is referencing an unknown value.

So, is there a way to declare the constants before the class decloration?

Or is there some other way to do this that I’m missing?

Source: Windows Questions C++

LEAVE A COMMENT