Why do c/c++ interviews always ask me about the keyword const, can’t I answer?

clude<iostream>


//const 的本质是防止误操作
/*
* 1.用const修饰函数的参数
* 2.用const修饰函数的返回值
* 3.const成员变量
* 4.const成员函数
* 5.const修饰指针
*/







using namespace std;

//1.用const修饰函数的参数

void myPrintf(const int num)
{
    
    
	int a = 5;
	//num = 5;    //报错
	//num = a;	//报错
	const int b = 6;    //定义const变量的时候必须赋初始值
	
	cout << num << endl;
}


// 2.用const修饰函数的返回值
//如果给以“指针传递”方式的函数返回值加const 修饰,那么函数返回值(即指针)的内容不能被修改,
//该返回值只能被赋给加const 修饰的同类型指针
const int* func()
{
    
    
	
}






//3.const成员变量   防止对对象成员的误操作  
class A
{
    
    
public:

	A(int age, char* name);
	
private:

	const int m_age;
	const char* m_name;
};


//对于const修饰的成员变量 构造函数必须使用下面的参数列表初始化
A::A(int age, char* name) :m_age(age), m_name(name)
{
    
    

}


//下面的构造方式报错
/*A::A(int age, char* name)
{
	this->m_age = age;
	this->m_name = age;
}*/


//4.const 成员函数
//const成员函数不可以修改对象的数据, 不管对象是否具有const性质.
//它在编译时, 以是否修改成员数据为依据, 进行检查


class B
{
    
    
public:
	int m_a;
	char m_b;

	int B_func()const
	{
    
    
		//m_a++;//报错左值不可以修改
		//m_b++;//同理
	}
};


//5.const修饰指针

//5.1. const修饰指针-- - 常量指针  		指针指向可以改,指针指向的值不可以改
const int* a;
//5.2. const修饰常量-- - 指针常量   	指针指向不可以改,指针指向的值可以改
int* const b;

//5.3. const即修饰指针,又修饰常量		都不可以改
const int* const c;


int main()
{
    
    
	myPrintf(5);
	
	//int *a = func();   //报错
	const int* b = func();
	 

	
}

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/110912570