C++语言—类的const成员

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_x_m_m_q/article/details/82464842

const修饰普通变量:
在C++中,const修饰的变量已经为一个常量,具有宏的属性,即在编译期间,编译器会将const所修饰的变量进行替换。
const修饰类成员:

 const修饰类成员变量时,该成员变量必须在构造函数的初始化列表中初始化

 const修饰类成员函数,实际修饰该成员函数隐含的this指针指向的内容,该成员函数中不能对类的任何成员进行修改

class Date
{
public:
	Date(int year,int month,int day)
		:_year(year)  //_year只能在此处初始化
		,_month(month)
		,_day(day)
	{}
	void show() const
	{
//		this->_day = 2018;  //函数体内无法改变类成员变量
		cout << _year<<"-"<< _month<<"-"<< _day << endl;
	}
private:
	const int _year;
	int _month;
	int _day;
};

 在const修饰的成员函数可能需要对类的某个成员变量进行修改,该成员变量只需被mutable关键字修饰即可

来看看以下几种场景:

1. 和const对象可以调用非const成员函数const成员函数吗?

2. 非const对象可以调用非const成员函数和const成员函数吗?

3. const成员函数内可以调用其它的const成员函数和非const成员函数吗?

4. 非const成员函数内可以调用其它的const成员函数和非const成员函数吗?

通过以下代码及其中的注释理解这里的问题是很容易的:

class Date
{
public:
	Date(int year,int month,int day)
		:_year(year)
		,_month(month)
		,_day(day)
	{}

	void Displayinfo()  //非const函数
	{
		showinfo();  //非const成员函数可以调用const成员函数
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	void showinfo() const  //const函数
	{
//		Displayinfo();  //const成员函数不可以调用非const成员函数
		cout << _year<<"-"<< _month<<"-"<< _day << endl;
	}
private:
	const int _year;
	int _month;
	int _day;
};

void test1()
{
	const Date d1(2000,1,1);  //const对象
	Date d2(2018, 9, 6);  //非const对象

//	d1.Displayinfo();  //const对象不可以调用非const成员函数
	d1.showinfo();   //const对象可以调用const成员函数

	d2.Displayinfo();  //非const对象可以调用非const成员函数
	d2.showinfo();  //非const对象可以调用const成员函数
}

 关于类的const成员这块就说这么多

猜你喜欢

转载自blog.csdn.net/z_x_m_m_q/article/details/82464842
今日推荐