【四、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指针)
【五、运算符重载实例分析】

posted @ 2022-02-24 22:03  Mindtechnist  阅读(24)  评论(0编辑  收藏  举报  来源