C嘎嘎~~[类 下篇 之 日期类的实现]

6.const成员

6.1 const成员的引入

class Date
{
    
    
public:
    // 构造函数
	Date(int year = 2023, int month = 5, int day = 5)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}

	void Print()
	{
    
    
		cout << _year << " " << _month << " " << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
    
    
	Date d1(2023, 5, 8);
	d1.Print(); // 可以运行

	const Date d2(2023, 5, 9);
	d2.Print(); // error C2662: “void Date::Print(void)”: 
	           // 不能将“this”指针从“const Date”转换为“Date &”
}
  • 为什么会出现这种情况? 报错中的 “不能将 this指针从 const Date 转换为 Date&” 是什么意思??
  • 那么该如何解决这种权限的放大问题呢??

我们知道 this指针是不在 行参和实参中显示的, 车门是焊死的; 那我们如何把const 加到 this指针上呢?
这时候我们的祖师爷就引入了 const成员

6.2const成员的概念

将const 修饰的成员函数称为 const成员函数, 实际上const 修饰的是隐含的 this指针⇒ 表明在该成员函数中不能对类的任何成员进行修改

class Date
{
    
    
public:
    // 构造函数
	Date(int year = 2023, int month = 5, int day = 5)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}

	void Print() const
	{
    
    
		cout << _year << " " << _month << " " << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
    
    
	Date d1(2023, 5, 8);
	d1.Print(); 

	const Date d2(2023, 5, 9);
	d2.Print(); 
	
}

*****
2023 5 8
2023 5 9
*****

通过前面的例子, 我们不难发现: const函数是挺好用的⇐ 普通对象 和 const对象 都能调用 const成员函数.
那么我们嫩不嫩将每一个成员函数都变成 const成员函数?? ⇐ 答案是显而易见的: 当然是不能的, 因为有些成员函数是要去修改成员变量的, 变成 const成员函数就不能对成员变量进行修改了

只要成员函数内部不修改成员变量, 那么就用 const成员函数


补充:

  • 指针 和 引用有权限一说, 而其他的没权限一说~

7.日期类的实现

猜你喜欢

转载自blog.csdn.net/qq_67549203/article/details/130553469