Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class can't have constants of own type inside?

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.

like image 582
sklott Avatar asked Jul 09 '21 10:07

sklott


People also ask

Can a class have its own object?

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.

How do I declare a const in TypeScript class?

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.

Can a class be constant?

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.

How do you define const in class?

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.


Video Answer


2 Answers

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

like image 198
Jarod42 Avatar answered Oct 24 '22 07:10

Jarod42


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_;
};
like image 44
KevinZ Avatar answered Oct 24 '22 05:10

KevinZ