不。这个问题在不重复 什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?
这里提出的问题与描述为重复的链接没有任何相似之处。
第一个问题: 我在以下两种情况下使用 const_cast。其中之一有效。另一个没有。
1. int* const //有效。
在这种语法中,变量指向的地址不能更改。所以我使用 const_cast 如下,它可以工作:
`
int j=3;
int *k=&j;
int *m=&j;
int* const i=k;
const_cast<int*>(i)=m; //OK: since i=m would not work so cast is necessary`
2. const int* //不起作用。
指向的地址可以更改,但值不能更改(尽管可以通过使变量指向不同的地址来更改)。我使用的 const_cast 似乎在这里不起作用:
`
int j=9;
int *k=&j;
const int* i1=0;
i1=k; //OK
//*i1=10;//ERROR.`
所以我尝试通过各种方式进行如下类型转换,但没有任何效果:
const_cast<int*>(i1)=10;
const_cast<int*>(*i1)=l;
*i1=const_cast<int>(l);
*i1=const_cast<int*>(10);
第二个问题: 所有类型转换是否仅可用于指针和引用?以下示例在图片中没有指针或引用的情况下是否无效?
const int a=9;
int b=4;
const_cast<int>(a)=b; //cannot convert from 'int' to 'int'. why is compiler
//trying to convert from int to int anyways or fails
//when both the types are same.