C++之const用法解惑

本文详细解析了C++中const关键字的多种用途,包括修饰变量、函数形参及成员函数,强调了其在保证代码稳定性和提高编译效率方面的作用。并通过实例对比,阐述了在实际编程中正确使用const的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const用途

首先,说下最基本的const用途:
case1:const修饰变量,表示是常量,程序中不能更改,存放在常量存储区。
例如:

const int a = 100;

case2:const修饰函数形参,表示传入的参数在函数内部不能修改。
例如:

class Test
{
	public:
	Test(const Test& obj)	//自定义的拷贝构造函数
	{
		// obj在该函数内部不能更改
	}
};

case3:非静态成员函数后置const,表示成员函数隐含传入的this指针是const指针。那么在该成员函数里,任何修改它所在类的成员的操作都是不允许的!
注意:后置const只能加在非静态成员函数后,加到*非成员函数或者静态成员*后面都是错误的。
例如:

class Test
{
	public:
	int m_num;

	int getNum() const
	{
		m_num = 1;	//error,不能在后置const函数里修改成员变量
	}
	
	bool operator == (const Test& obj) const
	{
	}
}

易错点

先看个例子

// test.cpp
#include <iostream>
#include <list>
using namespace std;

class Test
{
	public:
	
	int m_num;

	Test()
	{
		cout << "call constructor function..no param.." << endl;
	}

	Test(int num)
	{
		cout << "call constructor function..1 param.." << endl;
		m_num = num;
	}

	Test(const Test& obj)
	{
		cout << "call copy constructor function.." << endl;
	}

	~Test()
	{
		cout << "call destructor function.." << endl;
	}

	bool operator   == (const Test& obj)
	{
		return false;
	}
};


int main()
{
	Test a(1);
	Test b(2);

	if (a==b)
		;
	
	return 0;
}

// compile cmd
// g++ -g test.cpp -o test

这个编译不会有错,即便==的重载函数没有加后置const,编译也没有错。

但是再看下面一个例子

// test.cpp
#include <iostream>
#include <list>
using namespace std;

class Test
{
	public:
	
	int m_num;

	Test()
	{
		cout << "call constructor function..no param.." << endl;
	}

	Test(int num)
	{
		cout << "call constructor function..1 param.." << endl;
		m_num = num;
	}

	Test(const Test& obj)
	{
		cout << "call copy constructor function.." << endl;
	}

	~Test()
	{
		cout << "call destructor function.." << endl;
	}

	bool operator   == (const Test& obj)
	{
		return false;
	}
};


int main()
{
	Test a(1);
	Test b(2);

	list<Test> list1;
	list1.push_back(a);
	list1.push_back(b);

	list <Test> list2;
	list2.push_back(a);
	list2.push_back(b);

	if (list1 == list2)
		;
	
	return 0;
}

// compile cmd
// g++ -g test.cpp -o test

这个编译就出错了,如下:
在这里插入图片描述
当使用了std里的一些模板类,比如(list、set、vector等等),如果没有严格加后置const,那么编译就会出错,因为list的==重载函数要求都是const类型,而Test类的==重载函数不指定后置const的话,无法确定在Test的==重载函数会不会修改Test的成员。

编码好习惯

1、如果一个非静态成员函数不会修改该类的成员变量,都强制加一下后置const。
2、如果传入函数的参数在函数内部不会修改的话,函数参数也应该加上const修饰。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值