面试必问之 const

主要用法如下

目录

1.常量 常指针 常引用

2.修饰函数参数(*)

2. 修饰函数参数(&)

3. 修饰成员函数


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;
}

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值