const修饰类的成员

一、const修饰类的成员变量

const修饰的成员变量相当于该变量是一个常量,所以只能在初始化列表上初始化。

class Date{
public:
	Date(int year = 1900, int month = 1)
		:_year(year)
		, _month(month)
		, _day(1)
	{}
private:
	int _year;
	int _month;
	const int _day;
};

二、const修饰成员函数

const修饰类的成员函数,实质上修饰的是成员函数影藏得this指针,表示该成员函数不能对类的成员变量做修改,所以const不可以修饰构造函数和析构函数和赋值运算符重载。this指针类型变为const Date* const this。如果还是想要修改某一个变量,可以在变量前面加一个关键字mutable。

//两个函数形成重载,因为this指针类型不一样
void display()const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	void display()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

(1)const对象不可以调用非const函数,只能调用const成员函数,因为非const函数可能修改对象成员变量值。

(2)非const对象可以调用任何成员函数,只不过优先调用非const成员函数。

(3)const成员函数不可以调用非const成员函数,只能调用const成员函数。因为非const成员函数需要this指针。

(4)非const成员函数可以调用任何成员函数。

猜你喜欢

转载自blog.csdn.net/weixin_41318405/article/details/84488750
今日推荐