一、程序与输出
1.1 对const变量 取地址
#include<iostream>
using namespace std;
#include <string>
//1、对const变量 取地址 ,会分配临时内存
void test01()
{
const int a = 10; //常量,放在符号表中,修改失败
int * p = (int *)&a;
*p = 1000;
cout << "a=" << a << endl;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出:
const int a = 10; 声明了一个常量 a,其值为 10。c++中 对于基础类型(整数,浮点数,字符) 系统不会给const变量开辟空间 ,会将其放到符号表中;
int * p = (int *)&a; 将常量 a 的地址强制转换为 int 类型的指针,并赋值给指针 p。
*p = 1000; 试图通过指针 p 来修改常量 a 的值为 1000,这是一种非法的操作,会导致未定义行为。
cout << “a=” << a << endl; 最终输出常量 a 的值,由于常量 a 的值在编译时已经确定为 10,因此输出的结果是 a=10。
1.2 使用普通变量 初始化 const变量
#include<iostream>
using namespace std;
#include <string>
void test02()
{
int a = 10;
const int b = a;
int *p = (int *)&b;
*p = 1000;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main(){
test02();
system("pause");
return EXIT_SUCCESS;
}
输出:
解析:
声明并初始化了一个整型变量 a,其值为 10。
声明并初始化了一个变量 b,其值为变量 a 的值,即 10,此时它的值在栈上,而非符号表。
将变量b的地址强制转换为 int *类型的指针,并赋值给指针 p。
通过指针p修改指针内容为1000
使用普通变量 初始化 const变量,可以通过指针间接修改其值
。
why?
当用变量给const变量赋值时,系统直接为其开辟空间 而不会把它放入符号表中
1.3 修饰自定义数据类型
#include<iostream>
using namespace std;
#include <string>
struct Person
{
string m_Name;
int m_Age;
};
void test03()
{
const Person p = {
"asasa",
5
};
//p.m_Age = 10;//直接修改失败
Person * pp = (Person *)&p;
(*pp).m_Name = "Tom";
pp->m_Age = 10;
cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}
int main(){
test03();
system("pause");
return EXIT_SUCCESS;
}
输出:
解析:
定义了一个Person 结构体类型
在函数中生成一个const修饰的Person 结构体并初始化了其内容
直接修改其内容会失败
通过取地址的方式可以成功修改其内容;
why?
const 自定义数据类型(结构体、对象) 和数组系统会分配空间;
c++中当 对const变量取地址的时候 系统就会给它开辟空间;
二、分析与总结
1.
const常量无法直接、间接修改其值
2.使用普通变量 初始化 const变量,可以通过取地址方式间接修改其值
3.const修饰自定义数据类型,可以通过取地址方式间接修改其值
参考链接
该文对const内存分配有更详细的阐述:有兴趣可以看一下
C和C++中const变量内存分配问题详解