054关于const

注:IDE vs2013


const定义常量

#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
	const int x = 3; 
	system("pause");
	return 0;
}

此时的x为一个常量,不能再给x赋值,比如x=5;就是错误的;
此时const相当于#define

const与指针

1

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
	int x = 3;
	int y = 4;
	const int *p = &y;
	cout << *p << "," << x << "," << y << endl;
	p = &x;
	cout << *p << "," << x << "," << y << endl;
	x = 5;
	cout << *p << "," << x << "," << y << endl;
	system("pause");
	return 0;
}

const int *p = &y;等价于int const *p = &y;,此时定义*p为一个常量,不能为其赋值,比如*p=10;就是错误的,但是可以对p赋值,上述程序相当于将p的指向由y改向x,并且可以通过改变x来改变*p
如图:

2

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
	int x = 4;
	int z = 5;
	int *const q = &z;
	cout << *q << "," << z << endl;
	//q = &x; // 错误
	*q = 10;
	cout << *q << "," << z << endl;
	z = 6;
	cout << *q << "," << z << endl;
	system("pause");
	return 0;
}

将q定义为常量,不能对q赋值,即不能改变q的指向,但是可以对*q赋值,同时也会改变z的值,z的改变也会改变*q

const与引用

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
	int x = 3;
	int y = 4;
	int const &z = x;
	cout << z << ',' << x << endl;
	//z = y; //错误
	x = 5;
	cout << z << "," << x << endl;


	system("pause");
	return 0;
}

不能再对z赋值,但是可以改变x从而对z进行改变。

指针与引用

#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
	int x = 10;
	int *p = &x;
	cout << x << "," << *p << endl;
	cout << &x << "," << p << endl;

	system("pause");
	return 0;
}

x *p表示数字
&x p表示地址

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值