C++中的const用法

概述: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();
}

注释:

上述资料为个人学习总结笔记,学习资源来自 (此处插入超链接)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值