C++ 如何初始化一个围绕另一个类型的变量?
我能做到C++ 如何初始化一个围绕另一个类型的变量?,c++,types,C++,Types,我能做到 class Draw { public: Draw(); static const Shape_f32 shape; } 但是如果我想将形状的内部类型初始化为某个值呢?像 shape.side.value = 5.0; 我尝试了以下不同的解决方案: 一, 我无法在此对类型形状\u f32进行任何修改。那么,我想做的是可能的吗?似乎我需要创建一个接受值的类型初始值设定项 形状f32的定义 typedef struct Shape_f32_ { PI_si
class Draw
{
public:
Draw();
static const Shape_f32 shape;
}
但是如果我想将形状的内部类型初始化为某个值呢?像
shape.side.value = 5.0;
我尝试了以下不同的解决方案:
一,
我无法在此对类型形状\u f32
进行任何修改。那么,我想做的是可能的吗?似乎我需要创建一个接受值的类型初始值设定项
形状f32的定义
typedef struct Shape_f32_
{
PI_side side;
} Shape_f32;
typedef struct PI_side_
{
float value;
} PI_side;
#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;
}
您可以使用列表初始化:
inline static const Shape_f32 shape {
.side {
.value = 5.0,
},
};
但是,在C++20之前,您不能使用指定的初始化器,您需要按照成员声明的顺序初始化成员
另外,如果在标题中定义静态变量,则应在odr使用时将其声明为内联。对于您的情况,类定义外的简单初始值设定项列表应足够(如果您知道Shape_f32内的所有字段)
#包括
#包括
typedef结构PI_侧_
{
浮动值;
}皮尤侧;
typedef结构形状_f32_
{
皮尤侧;
}形状_f32;
结构Foo{
公众:
float get(){return bar_uu.side.value;}
私人:
静态常数形状为32巴;
};
//定义在类之外,最好将此行放在使用“Foo”的.cpp内
const Shape_f32 Foo::bar_f32={5};
int main(){
Foo-var;
std::cout请发布Shape_f32
的定义。你知道如何定义静态类成员吗?@KamilCuk添加了!是的,这是在C++20之前,我不确定如何按照声明顺序初始化。@FelixRosén只需从示例中删除变量名、点前缀和等号。并为任何m添加初始值设定项前面的余烬要有特定的值。是的,我只是这样做:static const Shape_f32 Shape{{{5.0}
inline static const Shape_f32 shape {
.side {
.value = 5.0,
},
};
#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;
}