简体   繁体   English

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

[英]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. 在此示例中,未设置Color c变量。 but c1 was set successfully. 但是c1设置成功。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以初始化静态 const 类成员吗? - Can I initialize static const class member? 我可以统一初始化模板类的静态const成员吗? - Can I uniformly initialize a static const member of template class? 如何初始化 static const 成员,它是另一个 class 的数组,并使用它? - How to initialize static const member that is array of another class, and use it? C ++为什么我可以在类定义中初始化静态const char而不是静态const double? - C++ Why can I initialize a static const char but not a static const double in a class definition? 如何在 c++11 中初始化作为类成员的静态常量向量? - How can I initialize a static const vector that is a class member in c++11? 如何初始化类中的静态const指针? - How to initialize static const pointer in a class? 类中的Const静态函数指针〜如何初始化它? - Const Static Function Pointer in Class ~ How to initialize it? 为什么我不能在类中初始化非常量静态成员或静态数组? - Why can't I initialize non-const static member or static array in class? 是否可以在C ++中的类中初始化静态const成员对象? - Is it possible to initialize static const member object in a class in C++? 如何使用数据 object 上的 const 指针初始化 class - How to initialize a class with a const pointer on a data object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM