我正在尝试编译以下代码,但出现 C2440 (visual studio) 错误。我尝试查看其他资源以寻求帮助,但找不到很好的解释。
int main()
{
int a = 100;
SomeFunction(&a);
}
void SomeFunction(const int* value)
{
//This line of code gives me the error.
int* variable = value;
cout << "Value is " << *Variable << " end" << endl;
}
我知道我可以使用 int* variable = const_cast<int*> (value);
解决这个问题,但我仍然不明白为什么上面的代码会导致问题。
最佳答案
错误很明显 - 指针转换不能删除 const
限定符;否则,您可能会违反常量:
int* variable = value; // Not allowed - but if it were...
*variable = 42; // BOOM! changed a constant.
如果你不想改变指向的值,那么保持它const
const int* variable = value;
如果你确实想改变它,那么首先不要让它成为const
:
void SomeFunction(int* value)
I know I can solve this problem by using
const_cast
这是个坏主意 - 如果您滥用 const_cast
并尝试修改常量对象,您将得到未定义的行为。您应该尽可能使用 const
,但不要在您想要修改某些内容时使用。
关于c++ - 无法从 const int* 转换为 int*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916791/