Const decorated member function

Const decorated member function

Add const after the member function , const modifies the object pointed to by the this pointer, that is, to ensure that the object calling this const member function will not be changed within the function.

class Date
{
public:
	
	void Display()
	{
		cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;
	const Date d2;
	d1.Display();
	d2.Display();
	return 0;
}

For the above program, d1 calls Display ( Date* this ), &d1 is of type Date* . And the type of &d2 is const Date* . The content of d2 cannot be modified, the Date* type can be modified, and the types do not match, so calling d2 will cause an error.

To call d2 of const type, the member function must be modified by const .

void Display1()const
	{
		cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
	}

This function can be called by d1 and d2 at the same time . d1 can be modified, the permissions are reduced when called by Display() const , and cannot be modified inside this function. Since Display() and Display1 ( ) const are two types, they can exist at the same time . 

For const objects and non-const member functions, there are the following situations :

1 ) const objects can call const member functions ;

2 ) Non- const objects can call non- const member functions;

3 ) Const objects cannot call non- const member functions ; for example: d2.Display();

4 ) Non- const objects can call const member functions; d1.Display 1 ();

For const member functions and other const member functions and non-const member functions, there are the following relationships:

class AA

{
public:
	void fun1()
	{
		fun2();//this->fun2();
		this->fun1();//Case 2
	}
	void fun2(){ }
private:
	int a;
};



class AA
{
public:
	void fun1()
	{
		fun2();//Case 4
		this->fun1();
	}
	void fun2()const
	{
		fun1();//Case 3, error
fun2();//Case 1
	}
private:
	int a;
};

1 ) const member functions can call const member functions;

2 ) Non- const member functions can call non- const member functions;

3 ) const member functions cannot call non- const member functions;

4 ) Non- const member functions can call const member functions;


 




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528184&siteId=291194637