内容参考于《21天学通C++》(第八版)
不去纠结C++的原理和细节,从C的角度去学习C++,再通过C++项目去加深理解
十二.单目运算符重载
1. 示例
#include <iostream>
using namespace std;
class Date
{
private:
int day, month, year;
public:
Date(int inMonth, int inDay, int inYear)
: month(inMonth), day(inDay), year(inYear) {};
Date & operator ++ () // prefix increment
{
++day;
return *this;
}
Date & operator -- () // prefix decrement
{
--day;
return *this;
}
void DisplayDate()
{
cout << month << " / " << day << " / " << year << endl;
}
};
int main()
{
Date holiday(12, 25, 2016); // Dec 25, 2016
cout << "The date object is initialized to: ";
holiday.DisplayDate();
++holiday; // move date ahead by a day
cout << "Date after prefix-increment is: ";
holiday.DisplayDate();
--holiday; // move date backwards by a day
cout << "Date after a prefix-decrement is: ";
holiday.DisplayDate();
return 0;
}
运行结果
The date object is initialized to: 12 / 25 / 2016
Date after prefix-increment is: 12 / 26 / 2016
Date after a prefix-decrement is: 12 / 25 / 2016
2. 转换运算符
cout << holiday; // error in absence of conversion operator
将导致这样的编译错误: error: binary ‘<<’ : no operator found which takes a right-hand operand of type ‘Date’ (or there is no acceptable conversion)。这种错误表明, cout 不知道如何解读 Date 实例,因为 Date类不支持这样的运算符,即将 Date 对象的内容转换成 cout 能够接受的类型。然而, cout 能够很好地显示 const char*:
因此,要让 cout 能够显示 Date 对象,只需添加一个返回 const char*的运算符:
#include <iostream>
#include <sstream> // new include for ostringstream
#include <string>
using namespace std;
class Date
{
private:
int day, month, year;
string dateInString;
public:
Date(int inMonth, int inDay, int inYear)
: month(inMonth), day(inDay), year(inYear) {};
operator const char*()
{
ostringstream formattedDate; // assists string construction
formattedDate << month << " / " << day << " / " << year;
dateInString = formattedDate.str();
return dateInString.c_str();
}
};
int main()
{
Date Holiday(12, 25, 2016);
cout << "Holiday is on: " << Holiday << endl;
// string strHoliday (Holiday); // OK!
// strHoliday = Date(11, 11, 2016); // also OK!
return 0;
}
运行结果
Holiday is on: 12 / 25 / 2016