Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a static const object in a class and use it?

Tags:

c++

c++11

So I have

// MyClass.h
class MyClass
{
private:
    static const Color::Color myColor
public:
    void SomeMethod();
}

// MyClass.cpp

const Color MyClass::myColor = Color::Color::Blue;
// or
const Color MyClass::myColor(Color::Color::Blue);

void MyClass::SomeMethod()
{
    Color c = this->myColor;
    Color c1 = Color::Color::Blue;
}

In this example, the Color c variable was not set. but c1 was set successfully.

like image 829
Pittfall Avatar asked Jan 30 '26 03:01

Pittfall


2 Answers

In general, I recommend providing a fully compilable example that shows your issue. Below I've included what looks like your test case, which works as expected.

#include <cassert>

enum class Color {
    Red = 1,
    Blue = 2
};

class MyClass {
    private:
        static const Color myColor;
    public:
        void SomeMethod();
};

const Color MyClass::myColor = Color::Blue;

void MyClass::SomeMethod()
{
    Color c = this->myColor;
    Color c1 = Color::Blue;

    assert(c == Color::Blue);
    assert(c1 == Color::Blue);
}

int main() {
    MyClass x;
    x.SomeMethod();
}
like image 50
Bill Lynch Avatar answered Feb 01 '26 18:02

Bill Lynch


try

    class MyClass
{
private:
    static const Color::Color myColor = Color::Color::Blue;
public:
    void SomeMethod();
};
like image 23
akrabi Avatar answered Feb 01 '26 19:02

akrabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!