int main(){
char *p = "a";
int i = (int)"a";
int i2 = (int)p;
//int i3 = static_cast<int>(p);
int i5 = reinterpret_cast<int>(&p);
cout << p<<endl;
cout << &p << endl;
cout << i << endl;
cout << i2 << endl;
//cout << i3<< endl;
cout << i5 << endl;
cout << i5 << endl;
* cout << i5 << endl;
}
从执行结果来看,i和i2的值是一样的。
p是指向字符串,
&p打印的是p的地址
int i = (int)"a";
这个是将"a"的结果转换为int类型。因为字符串的返回值是其首地址,也就是我们将字符串“a”的首地址做转化,转为为int型,
而i2是将p做强制类型转换,转换为int并打印,因为p的内容就是字符串“a”的首地址,所以两者的值是相等的
int i2 = (int)p;
真实指针做得很好的一件事是,支持隐式转换。子类对象指针可以隐式转换为基类指针。指向 non-const对象的指针可以转换为指向const对象。