主要用法如下
目录
1.常量 常指针 常引用
//const 常量不能改变
const int x = 5;
//x = 12;
常指针不能通过指针改变变量的值,但是可以改变变量的指向。
//const 常指针
int x,y;
const int * p= &x;
// *p= 2; error!!!
y = 3;
p = &y;
常引用不能通过引用改变变量的值,但是可以变量的值。
int x;
const int &r = x;
//r = 3;
x = 4;
2.修饰函数参数(*)
void print(const int * p,int len) {
//只读操作,traverse等,不能修改
cout << p[2];
}
int main()
{
//freopen("1.txt", "r", stdin);
int s[] = {1,2,3};
print(s, sizeof(s) / sizeof(int));
return 0;
}
2. 修饰函数参数(&)
struct date{
int year;
int month;
int day;
};
//可写
void initial(struct date & t){
t.year = 2019;
t.month = 9;
t.day = 7;}
//只读
void display(const struct date & t){
cout << t.year << "/" << t.month << "/" << t.day;
}
int main(){
struct date t;
initial(t);
display(t);
return 0;
}
3. 修饰成员函数
class complex {
public:
complex(double x, double y) :real(x), imag(y) {}
void get_real() const {
cout << real;
}
void get_imag() {
cout << imag;
}
private:
double real;
double imag;
};
int main()
{
//freopen("1.txt", "r", stdin);
complex c(1, 2);
const complex d(1, 3);
c.get_imag();
c.get_real(); //非const对象随便调用
//d.get_imag(); //const 对象只能调用const成员函数
d.get_real();
return 0;
}