我能做到
class Draw
{
public:
Draw();
static const Shape_f32 shape;
}
但是,如果我想将shape的内部类型初始化为某个值,该怎么办呢? 喜欢
shape.side.value = 5.0;
我试着做了这些不同的解决方案:
1。
class Draw
{
public:
Draw();
static const Shape_f32 shape.shape.value = 5.0;
}
class Draw
{
public:
Draw() {
shape.side.value = 5.0;
};
static const Shape_f32 shape;
}
我无法对shape_f32
类型进行任何修改。 那么我想做的事情可能吗? 似乎我需要创建一个接受值的类型初始值设定项。
Shape_f32的定义
typedef struct Shape_f32_
{
PI_side side;
} Shape_f32;
typedef struct PI_side_
{
float value;
} PI_side;
您可以使用列表初始化:
inline static const Shape_f32 shape {
.side {
.value = 5.0,
},
};
然而,在C++20之前,您不能使用指定的初始值设定项,而是需要按照成员声明的顺序初始化它们。
附注。 如果您在头中定义了静态变量,那么您应该将其声明为内联的,以防您ODR使用它。
对于您来说,在类定义之外的简单初始值设定项列表就足够了(如果您知道Shape_f32内部的所有字段)
#include <iostream>
#include <string>
typedef struct PI_side_
{
float value;
} PI_side;
typedef struct Shape_f32_
{
PI_side side;
} Shape_f32;
struct Foo{
public:
float get() {return bar_.side.value;}
private:
static const Shape_f32 bar_;
};
// definition outside the class, it would be best if this line is inside .cpp where you are using "Foo"
const Shape_f32 Foo::bar_ = {5};
int main() {
Foo var;
std::cout << var.get() << std::endl;
}
这通常输出5
编辑:它也适用于私有/受保护的成员