重载流操作符
c++ 允许对操作符进行重载
不能被重载的操作符只有5个
1. .(成员访问运算符)
2. *(成员指针访问运算符)
3. ::(域运算符)
4. sizeof (长度运算符)
5. ?: (条件运算符)对流的重载最好不要声明成类的成员函数。详细内容见C++Primer 第14章
举例:对一个类重载‘输入输出流’
class Time
{
public:
Time(int h = 0, int m = 0, int s = 0):hour(h), min(m), sec(s){}
Time &operator++(); //前缀 ++a a = a+1; return a;
Time operator++(int);//后缀 a++ temp = a; a = a + 1,return temp;
friend ostream &operator<<(ostream &out, const Time &t);
friend istream &operator>>(istream &in, Time &t);
private:
int hour;
int min;
int sec;
};
ostream &operator<<(ostream &out, const Time &t)
{
out << "Time: " << t.hour << "." << t.min << "." << t.sec;
return out;
}
istream &operator>>(istream &in, Time &t)
{
in >> t.hour >> t.min >> t.sec;
if(!in)
cout << "back..." << endl;
return in;
}
重载++ 操作符
Time &Time::operator++() //前缀
{
if(++sec==60)
{
sec = 0;
min++;
}
if(min==60)
{
min = 0;
hour++;
}
if(hour==24)
hour = 0;
return *this;
}
Time Time::operator++(int) //后缀
{
Time temp;
temp = *this;
if(sec++==60)
{
sec = 0;
min++;
}
if(min==60)
{
min = 0;
hour++;
}
if(hour==24)
hour = 0;
return temp;
}
推荐:双目运算符一般声明成友元, 而单目运算符一般声明成类成员。
具体如下:
A.赋值=、下标[]、调用()、和成员访问->等操作符必须定义为类的成员函数;
B.和赋值操作类似,复合赋值操作运算符+= -=等,应定义为类成员函数。
C.改变类状态或与给定类型紧密联系的其他一些操作符,如自增、自减和解引用,通常定义为类成员函数;
D.对称的操作符,如算术、相等、关系运算符、位操作符,通常定义为普通函数(友元)。
++ – 这两个运算符有特殊意义
&& || 这两个有短路功能