c++中const修饰成员函数的问题

问题引入:
看下面这一段代码:

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();   //编译报错
}
  • 为什么会产生这种情况呢?
    是因为类内部的this指针,它的类型是 Date * const 类型,它指向的地址不可修改,但是指向的内容是可以修改的。而上图中的d2,const的内容是不可修改的,调用Print()之后,会产生权限放大的错误,因此编译不通过。
  • 如何修改这种错误呢?
    只需要在成员函数后面,加上const即可修改this指针的类型变为:const Date* const 类型。改成这样后,虽然d1调用会产生权限缩小,但这种问题是允许发生的,不会报错。

在这里插入图片描述


  • const对象可以调用非const的成员函数吗?
    不可以,调用后会权限放大,不可以。

  • 非const对象可以调用const的成员函数吗?
    可以,调用后权限缩小,可以发生。

  • const成员函数内可以调用其它的非const成员函数吗?
    不可以,同样是调用后权限放大。

  • 非const成员函数内可以调用其它的const成员函数吗?
    可以,权限缩小允许发生。


因此为了防止这样的事情再发生,如果我们确定不会修改这个函数的参数,那么我们就使用const来修饰它,避免发生权限的问题。而且只有指针和引用会产生权限的问题。

猜你喜欢

转载自blog.csdn.net/weixin_45153969/article/details/132197374