qfedu-cpp-level/day7/d17.cpp

43 lines
1.1 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// const 转换
#include <iostream>
using namespace std;
void change(const int *p, int value)
{
int *q = const_cast<int *>(p); // 转换为非 const 指针
*q = value;
}
int main()
{
int a = 10;
const int b = 30; // 存储在符号表,在栈中没有空间
// 1. 将变量转化为 const 引用变量【可以】
const int &a1 = const_cast<const int &>(a);
// 2. 将变量地址转化为 const 指针变量【可以】
const int *a2 = const_cast<const int *>(&a);
// 3. 去掉 b 的 const 修饰
// b 在取地址时在占中开辟空间b1 指向空间
// int b1 = const_cast<int>(b);【不可以】
int &b1 = const_cast<int &>(b);
b1 = 100;
cout << "b = " << b << endl;
cout << "b1 = " << b1 << endl;
// 4. 去掉 a2 的 const 修饰
int *a3 = const_cast<int *>(a2);
*a3 = 200;
cout << "*a2 = " << *a2 << endl;
cout << "*a3 = " << *a3 << endl;
// 5. 将 a3 转化为 const 指针变量【可以】
const int *a4 = const_cast<const int *>(a3);
// *a4 = 100;
cout << "*a4 = " << *a4 << endl;
cout << "*a3 = " << *a3 << endl;
return 0;
}