Problems with const modified member functions in c++

Problem introduction:
Look at the following piece of code:

class Date
{
    
    
public:
 Date(int year, int month, int day)
 {
    
    
 _year = year;
 _month = month;
 _day = day;
 }
 void Print()
 {
    
    
 cout << "Print()" << endl;
 cout << "year:" << _year << endl;
 cout << "month:" << _month << endl;
 cout << "day:" << _day << endl << endl;
 }
//	void Print() const
//	{
    
    
//	cout << "Print()const" << endl;
//	cout << "year:" << _year << endl;
//	cout << "month:" << _month << endl;
//	cout << "day:" << _day << endl << endl;
//	}
private:
 int _year; // 年
 int _month; // 月
 int _day; // 日
};
void Test()
{
    
    
 Date d1(2022,1,13);
 d1.Print();   //正常运行
 const Date d2(2022,1,13);
 d2.Print();   //编译报错
}
  • Why does this happen?
    It is because the this pointer inside the class, its type is Date * const type, the address it points to cannot be modified, but the pointed content can be modified. In the above figure, the content of d2 and const cannot be modified. After calling Print(), an error of enlarging permissions will occur , so the compilation fails.
  • How to fix this error? Just add const
    after the member function to modify the type of this pointer to: const Date* const type. After changing to this, although the d1 call will result in narrowing of permissions, this kind of problem is allowed to happen and no error will be reported.

insert image description here


  • Can a const object call a non-const member function?
    No, the authority will be enlarged after calling, no.

  • Can a non-const object call a const member function?
    Yes, the rights can be narrowed after the call, and it can happen.

  • Can const member functions call other non-const member functions?
    No, it is also the privilege amplification after calling.

  • Can non-const member functions call other const member functions?
    Yes, privilege narrowing allows to happen.


Therefore, in order to prevent such things from happening again, if we are sure that we will not modify the parameters of this function, then we use const to modify it to avoid permission problems. And only pointers and references create permission issues.

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/132197374