c++查漏补缺(1)

目录

1.explicit关键字

2.static关键字

3.友元函数


1.explicit关键字

explicit关键字是在构造函数要使用的关键字。可以防止“隐式构造”,例如:

#include<iostream>

using namespace std;

class Date
{
public:
	explicit Date(int year, int month=1, int day=1)
		:_year(year),_month(month),_day(day)
	{}

	Date& operator=(const Date& date)
	{
		//防止自身拷贝
		if (this != &date)
		{
			_year = date._day;
			_month = date._month;
			_day = date._day;
		}
		return *this;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1 = 2022;
	return 0;
}

本来,编译器会根据2022隐式构造一个Date,然后拷贝构造,加上explicit就可以防止这种情况。

加上explicit关键字可以保证书写规范。 


2.static关键字

静态成员放在静态区,所有对象共享。

静态成员必须类外进行定义,类内只能作为声明。

静态成员函数没有this指针,只能访问静态成员。


3.友元函数

问题:如何在一个类中实现<<的重载?

如果直接operator重写<<,我们会发现隐藏的this会占据第一个参数的位置。

导致我们就算完成也只能写出a<<cout之类的代码。

友元函数就是一个普通函数,不同的就是通过在类内进行的声明,可以直接使用类内的私有成员。

看看代码测试和结果吧:

#include<iostream>

using namespace std;

class Date
{
	//友元关键字friend
	friend ostream& operator<<(ostream& _cout, const Date& date);
public:
	Date(int year, int month=1, int day=1)
		:_year(year),_month(month),_day(day)
	{}
private:
	int _year;
	int _month;
	int _day;
};

//友元函数需要在类外定义
ostream& operator << (ostream& _cout, const Date& date)
{
	_cout << date._year << "-" << date._month << "-" << date._day;
	return _cout;
}
int main()
{
	
	Date d1(2023,8,26);
	cout << d1;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会敲代码的运气选手^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值