设为首页 加入收藏

TOP

C++学习笔记之---控制变化的const
2015-11-21 00:57:54 来源: 作者: 【 】 浏览:1
Tags:学习 笔记 --- 控制 变化 const
//const与基本数据类型
//const与指针类型
#include 
  
   
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 
  
   
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 
  
   
using namespace std;
int main()
{
	const int x = 3;
	x = 5;
	return 0;
}



  

?

结果:

\

?

?

?

#include 
  
   
using namespace std;
int main()
{
	int x = 2;
	int y = 5;
	int const *p = &x;
	cout<<*p<
    
    \
    

?

?

?

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



     

?

?

//函数使用const

?

?

//函数使用const
#include 
     
      
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 <
       
       \
       

?

?

?

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

\

?

?

?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Selenium_WebDriver操作iFrame日.. 下一篇C++用纯虚函数实现协议委托的例子

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: