【四、const与this指针详解】详解C与C++中const的异同,类中的const

1.const的基础知识

const放在不同位置所代表的含义:

{
    int const a;
    const int a; //二者一样,表示变量a是一个常量(只读属性)
}

{
    const int* p; //指针所指向的内存空间不可修改//指向常整形的指针
    int* const p; //指针变量本身不可修改,即指针的指向不可修改//常指针
    const int* const p; //指针的指向和指针指向的内存空间都不可修改
}

//在指针做函数参数的时候可以加 const 防止指针误修改
void func(const char* p);

在C++中,引用其实就是一个常指针,所以引用所占空间大小等于指针(引用是变量的别名,变量是内存的别名)。

//C++中引用的实现
Type& t;
Type* const t;

2.C语言与C++中const的区别

在C语言中,const常量虽然不可修改,但是可以通过指针简介修改const修饰的变量

{
    int* p = NULL;
    const int a = 0;
    
    //a = 2; //不可修改
    
    p = (int*)&a;
    *p = 2;
}

在C++中,遇到const常量,会把它存到一个符号表,当使用到该常量时,直接用符号表中的值替换。C语言中的const常量是有自己的存储空间的,而C++中的const常量只有在声明为extern或使用&取址操作符的时候才为其分配地址。

3.const和#define

#define是预处理器进行的单纯的文本替换,const由编译器提供类型检查和作用域检查。

void function1()
{
    #define a 1   //全局
    const int b = 2; //作用域只在 function1() 函数内
}

void function2()
{
    cout << a << endl;
    //cout << b << endl;
}

关于C语言中的#define,typedef参考另一篇文章,链接如下:
嵌入式C语言基础:一文读懂#define与typedef的区别

4.类中的const

直接上代码吧:

#include <iostream>
using namespace std;

class ClassA
{
public:
	void SetValue(int a, int b) // void SetValue(ClassA* const this, int a, int b)
	{
		this->a = a;
		this->b = b;
		cout << "a = " << this->a << " b = " << this->b << endl;
	}

	void SetValue2(int a, int b) const // void SetValue(const ClassA* const this, int a, int b)
	{	//const修饰的是this指针指向的内存空间
		//this->a = a;
		//this->b = b;
		cout << "a = " << this->a << " b = " << this->b << endl;
	}

private:
	int a, b;
};

void FuncTest()
{
	ClassA A1;
	A1.SetValue(1, 2);

	A1.SetValue2(3, 4);
}

int main()
{
	FuncTest();

	system("pause");
	return 0;
}

系列文章

【三、类中的静态成员】静态成员变量与静态成员函数(static关键字、this指针)
【五、运算符重载实例分析】

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mindtechnist

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值