[英]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.