[英]c++ class constant of its own class
Basically, I would like to declare constants of a class within the class itself: 基本上,我想在类本身内声明一个类的常量:
class MyClass {
int itsValue;
public:
MyClass( int anInt) : itsValue( anInt) {}
static const MyClass CLASSCONST;
};
So I can access it like this; 这样我就可以访问它了;
MyClass myVar = MyClass::CLASSCONST;
But I can't find a way to initialize MyClass::CLASSCONST. 但是我找不到初始化MyClass :: CLASSCONST的方法。 It should be initilized inside the MyClass declaration, but at that point the constructor is not known.
应该在MyClass声明中将其初始化,但是那时构造函数是未知的。 Any one knowing the trick or is it impossible in c++.
任何人都知道这个技巧,或者在c ++中是不可能的。
class MyClass {
int itsValue;
public:
MyClass( int anInt) : itsValue( anInt) {}
static const MyClass CLASSCONST;
};
const MyClass MyClass::CLASSCONST(42);
Here is a working example with definition outside the class. 这是一个在类之外具有定义的有效示例。 The class declaration has a
const static
member which is initialized outside the class as it is a static member and of type non-integral. 类声明具有
const static
成员,该成员在类外部初始化,因为它是静态成员且类型为非整数。 So initialization inside the class itself is not possible. 因此,无法在类内部进行初始化。
#include <iostream>
class test
{
int member ;
public:
test(int m) : member{m} {}
const static test ob ;
friend std::ostream& operator<<(std::ostream& o, const test& t)
{
o << t.member ;
return o;
}
};
const test test::ob{2};
int main()
{
std::cout << test::ob ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.