Home > database >  Reference Loop C
Reference Loop C

Time:09-27

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?

CodePudding user response:

This works and makes your class interface easier to read. Most of the time we want to move the actual functions to source files anyway.

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

        public:
        Color(int r, int g, int b):r(r), g(g), b(b)
        {
        }

        Color CloserBlackOrWhite();
        };

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

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

I would add comparison operators also.

CodePudding user response:

You don't need memory allocation here. All you need is to forward-declare your constant colours, and forward-declare your class to be able to do the first step. You also want a public constructor, and at least some public methods.

All this gives you:

class Color;

extern const Color BLACK;
extern const Color WHITE;

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

    public:
    Color(int r, int g, int b):r(r), g(g), b(b)
    {
    }

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

const Color BLACK = Color(0, 0, 0);
const Color WHITE = Color(255, 255, 255);
  • Related