无法将 const 数据类型传递到非 const 函数中

Cannot pass const data type into a non const function

本文关键字:const 函数 数据类型      更新时间:2023-10-16

不能将常量数据类型传递到非常量函数中。将 func 设置为键入 const 错误后在函数中分配一个值将可以理解地设置错误,因为它不可变,因为它的内部不可变常量类型的函数。

如何通过引用将常量可变量传递到非常量函数中,并允许函数的内容要修改?

错误 C2662:无效 CarFactory::set_values(Car &( 无法将此指针从 const 汽车到汽车

 // Tried this
 //Car& newCarData = const_cast<Car&>(myCar);
 const Car& myCar = volvo->GetBuild();
 // Tried this
 //Car& newCarData = const_cast<Car&>(myCar);
 set_values(&myCar);

 void CarFactory::set_values(const Car& myCar){
 // do some assigning here for mutable variables declared in the header
 }

应该能够在没有错误的情况下调用它并将数据传递给 set_values((。并且还要修改标题中设置的非常量变量。

如果要修改set_values中的Car对象,则必须向其传递一个非常量引用。但这意味着您的volvo->GetBuild()也必须返回一个非常量引用。

下面的

解决方案,不是很好,但适用于此。后门指针,如果你愿意的话。

CarFactory* ptr = const_cast<CarFactory*>(this);

最后,我很抱歉在问题中没有代码的最小工作版本。试图解释它,如果你知道常量,你也许能够反弹一些想法。提到的评论确实支持此解决方案,因此谢谢。