C++ 更改常量结构的成员值

C++ Changing the values of members of a const struct

本文关键字:成员 结构 常量 C++      更新时间:2023-10-16

我有一个在 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,如果要修改该函数中的引用对象。