C++_运算符重载_前缀自增与后缀自增

由于前缀自增与后缀自增在如果通过运算符重载在形式上相同,都为

以Date类为例 Date& operator++(Date &)(全局函数)/ Date& operator++( )(成员函数)无法区分。

故人为规定前缀自增与后缀自增运算符的表达形式:

由于编译器必须能够识别出前缀自增与后缀自增,故人为规定了用一个 int 区分,并没有实际的含义。


前缀自增示例 

Calendar& Calendar::operator++(){
	tick();
	return *this;
}


后缀自增示例

Calendar Calendar::operator++(int){
	
	Calendar temp = *this;
	tick();
	return temp;
	

	/*
	tick();
	return *this;
	*/

}

上面会出现3次析构,Temp会导致一次析构。

下面只有两次析构,并没有保存传进来的副本





头文件

#ifndef CALENDAR
#define CALENDAR
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <windows.h>
using namespace std;

class Calendar;

ostream &operator<<(ostream & output, Calendar &C);


class Calendar{
	friend ostream &operator<<(ostream & output, Calendar &C);

public:
	Calendar(int y = 2015, int m = 8, int d = 6, int h = 17, int mm = 9, int s = 0)
		:year(y), month(m), day(d), hour(h), minute(mm), second(s){
	}
	//operator 

	Calendar &operator++();
	Calendar operator++(int);

	void tick(){
		++second;
	}

	~Calendar(){
		cout << "Destructor" << endl;
	}

private:
	int day;
	int month;
	int year;
	int hour;
	int minute;
	int second;
	FILE *fp;
};

Calendar& Calendar::operator++(){
	tick();
	return *this;
}

Calendar Calendar::operator++(int){
	
	Calendar temp = *this;
	tick();
	return temp;
	

	/*
	tick();
	return *this;
	*/

}

ostream &operator<<(ostream & output, Calendar &C){
	output << ""
		<< setw(15) << "Year: " << C.year << " "
		<< setw(15) << "Month: " << C.month << " "
		<< setw(15) << "Day: " << C.day << " " << endl
		<< setw(15) << "Hour: " << C.hour << " "
		<< setw(15) << "Minute: " << C.minute << " "
		<< setw(15) << "Second: " << C.second << " " << endl;

	return output;
}

#endif



主函数
int main(){
	Calendar a;

	cout << a << endl;

	cout << ++a << endl;

	cout << a++ << endl;
	cout << a << endl;


	return 0;
}





©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页