运算符重载(一种形式的C++多态)
函数重载:同名函数的参数列表不同,但返回值不做要求。
写法
type type::operator+(const type & t) const{
...
}
一些限制
重载运算符不必是成员哈桑农户,但必须至少有一个操作数使用户定义的类型。这一限制防止了用户对标准类型进行重载运算符,但需要在类中将非成员函数声明为友元函数。
class Time{
public:
...
friend Time operator-(const Time& t1, const Time& t2); // 友元函数属于非成员函数,没有this指针,也不能用const修饰
...
private:
int hours;
int minutes;
}
Time operator-(const Time& t1, const Time& t2){ // 友元函数在定义中不需要写friend
Time temp;
if(t1.hours < t2.hours || (t1.hours == t2.hours && t1.minutes < t2.minutes) ) {
std::cout << "value error" << std::endl;
return temp;
}
else{
temp.minutes = t1.minutes < t2.minutes ?