简体   繁体   中英

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

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.

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();
}

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM