C++ 类和对象 拷贝构造函数 & 运算符重载

拷贝构造函数是什么呢
是构造函数的重载形式
只有单个形参(const),形参是本类 类类型对象的引用,对存在的类类型对象编译器自动调用
什么时候用到呢

class Data {
public:
	Data(int year = 1900, int month = 1, int day = 1) {
		_year = year;
		_month = month;
		_day = day;
	}

	Data(const Data& d) {// 则就是拷贝构造函数
		_year = d._year;
		_month = d._month;
		_day = d._day;
		cout << "Data(Data&)" << endl;
	}

	void SetData(int year, int month, int day) {
		_year = year;
		_month = month;
		_day = day;
	}
	void PrintData() {
		cout << _year << "-" << _month << "-"
			<< _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

和构造函数相同,拷贝构造函数在用户没有显式定义的时候会自己生成

那么在什么情况下会调用拷贝构造函数呢

int main() {
	Data d1;
	Data d2(2019, 7, 3);
	Data d3(d2);

比如上面这样

接着把运算符重载也说一下吧
你比如上面的时间类,我想看看两个对象表示的日期是不是相等的,那可以写一个函数,比如

bool IsSame(const Data& d) {
		return _year == d._year &&
			   _month == d._month&&
			   _day == d._day;
	}

这个函数是日期类的成员函数,要用在main里调用一下就行

但是麻烦,我想这样 d1 == d2
怎么办,有办法! 重载 "=="这个运算符就行

bool operator==(const Data& d) {
		 return _year == d._year &&
			    _month == d._month&&
			    _day == d._day;
	 
		 return true;
	 }

这样子就行

在要重载的运算符前面加上 operator 关键字,然后参数其实有个this,另一个是对象的引用

顺便把 != 也给出来吧

 bool operator!=(const Data& d) {
		 return !(*this == d);
	 }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值