const int m_a = 100; //分配到常量区
void fun()
{
int * p = (int *)&m_a;
*p = 200;
}
结论:编译成功,但是运行失败,修改失败
void fun()
{
const int m_b = 100; //分配到栈上
int * p = (int *)&m_b;
*p = 200;
cout << m_b << endl;
}
结论:运行成功,修改失败
因此c++ const可以称为常量
const变量默认是内部链接属性,加extern可以提高作用域
void fun()
{
const int m_b = 100; //分配到栈上
int * p = (int *)&m_b;
*p = 200;
}
同上分配的临时内存
void fun()
{
int a = 10;
const int m_b = a; //分配到栈上
int * p = (int *)&m_b;
*p = 200;
}
修改成功,因为分配了内存
struct Person
{
string m_Name;
int m_Age;
};
void test03()
{
const Person p;
//p.m_Age = 10; //直接修改失败
Person * pp = (Person *)&p;
(*pp).m_Name = "Tom";
pp->m_Age = 10;
cout << "姓名 " << p.m_Name << " 年龄" << p.m_Age << endl;
}
间接修改成功,分配了内存