x
using namespace std;
class People{
private:
double height;
double weight;
// mutable 表示该变量易变,可以被常方法修改
mutable int age;
// const类型数据只能在构造函数初始化列表初始化
const int score;
char *name;
public:
// 常方法
// const修饰的方法
char *getName() const {
addAge();
return name;
}
// void addAge(const People* const this);
void addAge() const {
age++;
}
People()
: name{ new char(20) }
, score(0)
, age(18)
, height(180)
, weight(65) {
strcpy_s(name, 20, "Axieyun");
}
};
const修饰的类型定义时必须赋值也就是初始化,在类中定义时,在参数列表初始化
即,不能先定义,后赋值
xxxxxxxxxx
const int a;
a = 1;
// 错误
应该这样
xxxxxxxxxx
const int a = 1; //正确
const int *p与int const *p等价:说明不能通过修改*p
来修改p指向的值
xxxxxxxxxx
int a = 1;
const int *p = &a;
(*p)++; //不能这样
xxxxxxxxxx
int a = 1, b = 2;
const int *p = &b;
p = &a; // 可以这样
int * const p: 说明不能修改p的值(地址)
即,不能
xxxxxxxxxx
int a = 1, b = 2;
int * const p = &b;
p = &a; // 不可以这样
xxxxxxxxxx
int a = 1;
int * const p = &a;
(*p)++; //可以这样
const int * const p :说明两种情况都不行