c++ - 无法从 const int* 转换为 int*

标签 c++

我正在尝试编译以下代码,但出现 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/

相关文章:

c++ - 对没有比较器或 lambda 函数的 vector 进行排序?

c++ - C++ 管道系统调用总是以 EOF 结尾吗?

C++ 文件解析参数个数

c++ - 如何通过正确的错误处理在 C++ 中实现阶乘函数?

c++ - 类中类的大小

c++ - connect()中如何获取SLOT的成员对象?

c++ - pthread_barrier_wait 在创建所有线程后挂起

c++ - GDB分步调试两个线程

c++ - 如何从枚举类型中获取 std::string?

c++ - C-LinkedList Append Function, with Bad Memory Address 错误