What I mean, is it possible to somehow do something like this?
class Color {
public:
static constexpr Color BLACK = {0, 0, 0};
constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}
private:
int r_;
int g_;
int b_;
};
Compilers complain about class Color
being incomplete when defining BLACK
constant.
A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine. And following program also works fine. // A class cannot have non-static object(s) of self type.
Use the readonly modifier to declare constants in a class. When a class field is prefixed with the readonly modifier, you can only assign a value to the property inside of the class's constructor. Assignment to the property outside of the constructor causes an error.
Constants cannot be changed once it is declared. Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword.
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. The value must be a constant expression, not (for example) a variable, a property, or a function call.
You might move definition outside:
class Color {
public:
static const Color BLACK;
constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}
private:
int r_;
int g_;
int b_;
};
constexpr Color Color::BLACK = {0, 0, 0};
Demo
Alternatively, you can change the static variable to a function call:
class Color {
public:
static constexpr Color BLACK() { return {0, 0, 0}; }
constexpr Color(int r, int g, int b) : r_(r), g_(g), b_(b) {}
private:
int r_;
int g_;
int b_;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With