c++ const用法讨论

主要有两种,一个针对变量,一个针对类

1.对于变量

  1. const int* a = new int; const意味着指针a的内容无法别改变
  2. int* const b = new int; const意味着无法改变指针,但可以改变指针指向的内容
  3. const int* const d = new int;// 既无法改变指针,也无法改变指针的内容

2.对于类

int GetX() const {// const意味着承诺不会修改实际的实体类
	// m_X = 2; // 这里m_X无法被修改,const意味着这个类是只读的
	return m_X;
}

假如有一个函数PrintEntity如下,const Entity& e意味着不改变这个类,那么如果调用int GetY() { return m_Y; }将会报错,即使这里并没有改变m_Y的值,因此对于GetY这个函数一般写两个定义GetY

void PrintEntity(const Entity& e) {// 我不想复制我的实体类
	//因为const Entity& e,他不能确定GetY是否修改了实体,所以必须GetY后面加上const
	// std::cout << e.GetY() << std::endl;

	std::cout << e.GetX() << std::endl;
}

代码片段如下:

#include <iostream>
#include "Log.h"

class Entity {
private:
	int m_X, m_Y;
	int* m_Z;
public:
	int GetX() const {// const意味着承诺不会修改实际的实体类
		// m_X = 2; // 这里m_X无法被修改,const意味着这个类是只读的
		return m_X;
	}

	int GetY() {
		return m_Y;
	}

	//为了避免PrintEntity函数中的情况,通常会有两个版本的Get函数
	int GetY() const {
		return m_Y;
	}

	const int* const GetZ() const{// 不修改指针,不修改指针的内容,不修改实际的实体类
		return m_Z;
	}

	void SetX(int x) {
		m_X = x;
	}
};

//void PrintEntity(const Entity& e) {// 我不想复制我的实体类
//	std::cout << e.GetX() << std::endl;
//}

void PrintEntity(const Entity& e) {// 我不想复制我的实体类
	//因为const Entity& e,他不能确定GetY是否修改了实体,所以必须GetY后面加上const
	// std::cout << e.GetY() << std::endl;

	std::cout << e.GetX() << std::endl;
}

int main() {

	Entity e;
	
	const int MAX_AGE = 90;

	const int* a = new int; // const意味着指针a的内容无法别改变

	// 1
	// *a = 2; // 这里会发现报错
	a = (int*)&MAX_AGE; // 这里是指针a的地址被改变,但是没有直接更改指针指向的内容,所有没报错吗
	std::cout << *a << std::endl;

	// 2. const
	int* const b = new int;//无法改变指针,但可以改变指针指向的内容
	const int* c = new int;//此处调换两者的位置是相同的作用
	// b = &MAX_AGE;// 这里会发现报错
	// b = (int*)&MAX_AGE;
	// b = nullptr;
	*b = 3;

	// 3.
	const int* const d = new int;// 既无法改变指针,也无法改变指针的内容
	std::cout << "hello" << std::endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值