我相信以下代码不应该编译通过,但是在g++中却可以编译通过!您可以在http://codepad.org/MR7Dsvlz上看到它的编译结果。
代码如下:
#include <iostream>
using namespace std;
int main() {
int x = 32 ;
// note: if x is, instead, a const int, the code still compiles,
// but the output is "32".
const int * ptr1 = & x ;
*((int *)ptr1) = 64 ; // questionable cast
cout << x ; // result: "64"
}
编译这个代码时,g++是否存在错误?
const_cast<int*>(ptr1)
- 虽然C语言风格的转换也可以,正如你刚才所看到的。 - Michael Anderson