c++ - const int 隐式转换 C++

标签 c++ casting constants const-cast

我想知道在使用指向常量整数的指针时变量之间是否存在某种隐式转换, 例如,如果我使用变量类型的地址 intconst int 它接受存储它, 但是,如果我使用普通的 pointer to int 它不允许存储 const int 类型的地址,这是为什么?提前致谢

int i=4;
const int ii=4;

//pointer to constant int 
const int *pci=&i; //OK.
pci=ⅈ //OK.
int *pi=ⅈ //ERROR invalid conversion.

最佳答案

第一个和第二个赋值将 pci 初始化为 conSTLy 指向 intconst int

所以您可能会遇到以下两种情况之一:

  • const int* 指向一个 int

    pci=&i;
    
  • const int* 指向一个const int

    pci=ⅈ
    

这两种情况都是安全的,因为您只是添加约束

通过做:

int *pi=ⅈ

您使一个 int* 指向一个 const int,这意味着您删除了一个约束

由于删除约束可能存在风险,因此这需要您使用 const_cast .

int* pi = const_cast<int*>(&ii);

请注意,强行删除 const 修饰符是一件事情 you should ask yourself twice if you really wanna do ,因为它还使 const 修饰符有些无意义,因为您将能够通过转换后的变量修改该“常量” 地址。

关于c++ - const int 隐式转换 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829646/

相关文章:

c++ - opencv - sailfishOS IDE

c++ - Const 静态成员函数 : is another approach available?

c# - C#'s equivalent to VB.NET' s 直播

c++ - switch-case 标签中的 C11 和常量表达式求值

c++ - 使用类 static const 整数初始化二维数组

c++ - 将函数名称作为 C++ 类中另一个函数的参数传递

C++ Visual Studio Unicode 混淆

C++ boost Asio : How do I have multiple clients?

java - 无法转换迭代器

ios - 为什么类型转换在 Swift 2.0 中的工作方式不同?