如何在类中初始化静态const对象并使用它?

时间:2014-05-23 16:36:15

标签: c++ c++11

所以我有

// 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;
}

在此示例中,未设置Color c变量。但是c1已成功设置。

2 个答案:

答案 0 :(得分:3)

一般情况下,我建议您提供一个完全可编辑的示例来说明您的问题。下面我列出了你的测试用例,它按预期工作。

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

答案 1 :(得分:2)

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