码迷,mamicode.com
首页 > 编程语言 > 详细

C++学习笔记之---控制变化的const

时间:2015-07-09 06:20:05      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

//const与基本数据类型
//const与指针类型
#include <iostream>
using namespace std;
int main()
{
	const int x = 10;
	//x = 20;             此处会报错!!!const修饰其值改变不了
	return 0;
}


int main()
{
	//1.const int *p = NULL;  与 int const *p = NULL等价
	int x = 3, y = 4;
	const int *p = &x;
	p = &y;						//此处正确
	//*p = 4;此处为错误的
	
	//2.int *const p = NULL;
	int *const p = &x;
	//p = &y;                   此处报错
	
	//3、const int * cont p = NULL;
	const int *const p = &x;
	//此处改变不了的
	return 0;
}



例子:

#include <iostream>
using namespace std;
int main()
{
	const int x = 3;
	x = 5;
	
	
	int x = 3;
	const int y = x;
	y = 5;

	int x = 3;
	const int * y = &x;
	*y = 5;


	int x = 3, z = 4;
	int *const y = &x;
	y = &z;

	const int x = 3;
	const int &y = x;
	y = &z;
	return 0;
}



结果如图:


具体请查看错误信息:


技术分享


技术分享


技术分享


代码如下:


#include <iostream>
using namespace std;
int main()
{
	const int x = 3;
	x = 5;
	return 0;
}



结果:

技术分享



#include <iostream>
using namespace std;
int main()
{
	int x = 2;
	int y = 5;
	int const *p = &x;
	cout<<*p<<endl;
	p = &y;
	cout<<*p<<endl;
	return 0;
}



技术分享


#include <iostream>
using namespace std;
int main()
{
	int x = 2;
	int y = 5;
	int const &z = x;
	z = 10;             //会报错
	x = 11;	
	return 0;
}




//函数使用const


//函数使用const
#include <iostream>
using namespace std;
void fun(int &a, int &b)
{
	a = 10;
	b = 22;
}
//函数有问题
//不能赋值
/*
void fun1(const int &a, const int &b)
{
	a = 33;
	b = 44;
}
*/


int main()
{
	int x = 2;
	int y = 5;
	fun(x, y);
	cout<<"函数没有const修饰的结果是: "<< x <<" , "<< y <<endl;
	/*
	int v = 3;
	int w = 4;
	fun1(v, w);
	cout<<"函数没有const修饰的结果是: "<<v<<" , "<<w<<endl;
	*/
	return 0;
}



技术分享



如果上例代码的注释去掉就会出现如下错误信息:

技术分享




版权声明:本文为博主原创文章,未经博主允许不得转载。

C++学习笔记之---控制变化的const

标签:

原文地址:http://blog.csdn.net/u012965373/article/details/46811205

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!