Home > Mobile >  Assigning static const within a class and outside, why the difference?
Assigning static const within a class and outside, why the difference?

Time:11-19

This is so wierd, i am coding a pixel manipulation library in C . So i want to have a class filled with color presets. Color is a class with a struct that looks like:

Color(int r, int g, int b, int a)

And if i declare it outside of any classes as:

static const Color COL_BLACK = Color(0, 0, 0, 255);

That shows no error in Visual Studio Code. But however when i structure like this:

class Colors {
public:
  static const Color Black = Color(0, 0, 0, 255);
};

The equal sign has a red squiggly line under it, but when i hover my mouse over it doesn't tell me what is wrong. What is wrong?

Note that i want it to be called like so:

Color newCol = Colors::Black;

CodePudding user response:

Since C 17 you can simply use inline like in the following:

#include <iostream>

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

    int r, g, b, a;
};

class Colors 
{
public:
    inline static const Color Black = Color(0, 0, 0, 255);
};

int main()
{
    Color c = Colors::Black;
    std::cout << c.r << "," << c.g << "," << c.b << "," << c.a << "\n";
}

CodePudding user response:

Read up a little on static initialization. In the meantime, in this case you could define Color with a constexpr ctor, like this:

struct Color
{
  const unsigned int r;
  const unsigned int g;
  const unsigned int b;
  const unsigned int a;

  constexpr Color( const unsigned int r, const unsigned int g, const unsigned int b, const unsigned int a ) : r(r), g(g), b(b), a(a)
  {}
};

And then you would initialize Colors like this:

class Colors
{
  public:
    static constexpr Color Black = Color(0, 0, 0, 255);
};
  • Related