无法将 const 数据类型传递到非 const 函数中
Cannot pass const data type into a non const function
不能将常量数据类型传递到非常量函数中。将 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);
最后,我很抱歉在问题中没有代码的最小工作版本。试图解释它,如果你知道常量,你也许能够反弹一些想法。提到的评论确实支持此解决方案,因此谢谢。
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 使用 std::string () const 函数启动线程或未来
- 如果我在 const 函数上使用指针,我可以返回什么?
- 为什么 const 函数返回左值而不是右值?
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 在 const 对象上调用非 const 函数
- 析构函数是否可以在 const 对象上调用非 const 函数
- C/C++ 如何在一次函数调用中交出 const 函数指针或简单指针
- 为什么我可以在C 11中使用const函数修改类
- 防止const函数被调用非const对象
- 如果C 中的支架重载运算符被声明为const函数
- C++:防止在 const 函数中更改指针的值
- 从const函数返回非const属性参考
- 调用指针参数从const函数指向的对象的操作员
- 在const函数中调用非CONST成员的非const函数
- 无法将 const 数据类型传递到非 const 函数中
- 这是检查 const 函数(如果是否创建某些内容)的更好方法
- 在 const 函数中从地图中未经选中读取
- 编译器不会为 "const" 和"not-const"函数给出不明确的错误吗
- 通过const函数中的参数索引返回std :: map的值