C++ 更改常量结构的成员值
C++ Changing the values of members of a const struct
我有一个在 types.h 中定义的结构,代码如下:
struct data_Variant {
FlightPlanSteeringDataRecord steeringData;
FlightPlanType flightPlan : 8;
MinitoteLegDataType legDataType : 8; // discriminent, either current or amplified
unsigned spare : 16;
union {
// currentLeg =>
CurrentLegDataRecord currentLegData;
// amplifiedLeg =>
AmplifiedLegDataRecord amplifiedLegData;
} u;
};
然后,我尝试将该结构的实例作为参数传递给名为 dialogue.cpp 的C++源文件中的函数:
void dialogue::update( const types::data_Variant& perfData){
...
}
我现在想更改此 update()
函数中该结构的某些成员的值。但是,如果我尝试像往常一样这样做,即
perfData.etaValid = true;
我收到一个编译错误,上面写着:"C2166:l 值指定常量对象"。据我了解,这是因为perfData
已被声明为常量变量。我这样想对吗?
由于我没有编写这部分代码,而只是想使用它来更新 GUI 上显示的值,因此我真的不想通过删除 const
关键字来更改perfData
变量,以防万一我破坏了其他内容。有没有办法更改已声明为 const 的变量的值?
我尝试在代码的另一部分声明相同的结构变量,而不使用 const
关键字,看看我是否可以在那里更改它的一些成员的值......即在 Interface.cpp 中,我将以下代码添加到名为 sendData()
的函数中:
types::data_Variant& perfData;
perfData.steering.etaValid = true;
perfData.steering.ttgValid = true;
但是,我现在在这些行上收到以下编译错误:
error C2653: 'types' is not a class or namespace name
error C2065: data_Variant: undeclared identifier
error C2065: 'perfData': undeclared identifier
error C2228: left of '.steering' must have class/ struct/ union
有没有办法更新此结构的值?如果是这样,我应该怎么做,我在这里做错了什么?
我已将以下函数添加到dialogue.cpp
源文件中,如答案所示:
void dialogue::setFPTTGandETAValidityTrue(
FlightPlanMinitoteTypes::FlightPlanMinitoteData_Variant& perfData)
{
SESL_FUNCTION_BEGIN(setFPTTGandETAValidityTrue)
perfData.steeringData.fpETAValid = true;
perfData.steeringData.fpTTGValid = true;
SESL_FUNCTION_END()
}
您可以为自己添加一个包装器。
void myupdate(dialogue& dia, types::data_Variant& perfData)
{
perfData.etaValid = true;
dia.update(perfData);
}
然后呼叫myupdate()
而不是dialogue::update()
。
你声明
void dialogue::update( const types::data_Variant& perfData){
...
}
该 const 是您说的声明:"我不会修改此函数中的引用对象"。如果你想在 dialog::update 中修改它,你必须删除 const 关键字。在我看来,包装不是一种解决方案,它会使代码更难维护。我也投票反对删除const_cast的常量。
正确的解决方案是从方法声明中删除 const,如果要修改该函数中的引用对象。
- 如何在C++中定义静态成员结构
- 使用模板化类的成员结构
- 初始化固定的 C 数组成员结构
- 指向成员结构的指针如何工作
- 如何将此“指针从外部类传递到成员结构
- 导致IAR ARM中出现错误的成员结构位字段元素的Initializer列表初始化
- 映射文件中成员结构的地址
- Visual C++ 模板类成员结构初始化语法糖
- C :初始化成员结构的静态字段的正确方法
- 如何在C 类的初始化器列表中使用未命名结构初始化成员结构
- 从成员结构的成员函数中访问类的成员?
- 模板化类的成员函数无法返回指向成员结构的指针?
- 重载非类型模板结构的成员结构的复制赋值运算符
- 灵气属性传播问题与单成员结构.
- 将具有 int* 成员C++结构编接到 C#
- 复杂的班级成员结构
- 将向量成员(结构)传递给函数
- 成员结构的前向声明
- 重载运算符<<用于模板结构中定义的成员结构
- 返回带有模板化类的类成员结构