const分配内存模型
对const变量取地址,分配临时内存
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test() {
const int a = 10;
int *p = (int *)(&a);
cout << "p=" << p << endl;
cout << "a=" << &a << endl;
cout << "p_address=" << &p << endl;
}
int main() {
test();
return EXIT_SUCCESS;
}
使用普通变量 初始化 const变量
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
void test() {
int a = 10;
const int b = a;
int *p = (int *)&b;
*p = 1000;
cout << " b = " << b << endl;
}
int main() {
test();
return EXIT_SUCCESS;
}
对于自定义数据类型
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
struct Person {
string m_Name;
int m_Age;
};
//对于自定义数据类型
void test() {
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;
}
int main() {
test();
return EXIT_SUCCESS;
}