天天看點

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;
}
           
C++_運算符重載_字首自增與字尾自增

繼續閱讀