概述:const 三种用法
作为关键字,const是一种规则,承诺某些东西是不变的(实际也可变)
1.变量转常量
用于程序中一直不变的量
#include <iostream>
#include <string>
int main()
{
const int MAX_AGE = 5;
//MAX_AGE = 2;//报错。const 常量 不可变
std:cin.get();
}
2.const与指针
可变
#include <iostream>
#include <string>
int main()
{
const int MAX_AGE = 90;
int* a =new int;
*a = 2;
//a = &MAX_AGE;//报错
a = (int*)&MAX_AGE;//绕开const 不报错
std:cin.get();
}
const位于指针左边,左定值,指针指向的值不可变。常量指针
#include <iostream>
#include <string>
int main()
{
const int MAX_AGE = 90;
const int* a =new int;
//int const* a =new int;//这两种写法一样
//*a = 2;//报错
a = (int*)&MAX_AGE;//不报错
std:cin.get();
}
const位于指针右边,右定向,指针指向不能改变。指针常量
#include <iostream>
#include <string>
int main()
{
const int MAX_AGE = 90;
int* const a =new int;
*a = 2;//不报错
a = (int*)&MAX_AGE;//报错
std:cin.get();
}
3.const与成员函数
只适用于类内 ,在成员函数名右边加const,表示该函数内不可改变类内变量
const函数内,若想改变类内变量,可以给对应变量设置mutable
class Entity
{
private:
int m_X, m_Y;
mutable int var;
public:
int Getx() const
{
var=2;//不报错
//m_X = 2;//报错
return m_X;
}
}
一点点拓展:
class Entity
{
private:
int* m_X, m_Y;
public:
const int* const Getx() const //返回一个不能被修改的指针
{
//m_X = 2;//报错
return m_X;
}
}
一点点拓展:
class Entity
{
private:
int m_X, m_Y;
public:
int Getx() const
{
//m_X = 2;//报错
return m_X;
}
}
void PrintEntity(const Entity& e){//不复制,效率更快
//常对象,只能调用常函数
std:cout <<e.Getx()<<std:endl;
}
int main()
{
Entity e;
const int MAX_AGE = 90;
int* const a =new int;
*a = 2;//不报错
a = (int*)&MAX_AGE;//报错
std:cin.get();
}
注释:
上述资料为个人学习总结笔记,学习资源来自 (此处插入超链接)