在c++中我们有时可能需要对类对象,进行算术运算和逻辑运算等操作,但是对于自定义类型的对象来说默认情况C++是不支持使用运算符的,如下面的日期类Date中所存在的问题,此时C++中引入了运算符重载,来解决这一问题。
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2023,9,25);
Date d2(2022,9,25);
d1>d2;//此时这里会直接报错
return 0;
}
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
int _year;
int _month;
int _day;
};
函数名 operator操作符
返回类型 看操作符运算后返回值是什么
参数,操作符有几个操作数,他就有几个参数
bool operator>(const Date& d1, const Date& d2)
{
if (d1._year > d2._year)
{
return true;
}
else if (d1._year == d2._year && d1._month > d2._month)
{
return true;
}
else if (d1._year == d2._year && d1._month == d2._month && d1._day > d2._day)
{
return true;
}
else
{
return false;
}
}
int main()
{
Date d1(2022, 1, 16);
Date d2(2022, 1, 31);
d1 > d2; // -》operator>(d1, d2)
cout << operator>(d1, d2) << endl;
return 0;
}
话不多说,以下面一段代码为例。
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
bool operator>(const Date& d)
// bool operator>(Date* const this, const Date& d)
{
if (_year > d._year)
{
return true;
}
else if (_year == d._year && _month > d._month)
{
return true;
}
else if (_year == d._year && _month == d._month && _day > d._day)
{
return true;
}
else
{
return false;
}
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 1, 16);
Date d2(2022, 1, 31);
d1 > d2; // d1.operator>(d2);
d1.operator>(d2);
return 0;
}
有些同学一定会问类中的bool operator>(const Date& d) 怎么只有一个参数了,以前不是有两个参数吗?大家是否还记得我写过的详谈C++this指针一文,在类中是有一个隐藏的指针的,这里你看到的函数只有一个参数,但实际上是有两个参数的,隐藏的this指针和const Date& d。可以把类中的bool operator>(const Date& d)方法翻译成如下代码,来加深大家的理解。
bool operator>(Date* const this, const Date& d)
{
if (this->_year > d._year)
{
return true;
}
else if (this->_year == d._year && this->_month > d._month)
{
return true;
}
//看到这里想必大家恍然大悟了吧!!!
请问下面的两种赋值运算符重载的方法A,B。你认为哪一种更好。
class Date
{
public :
Date(int year = 1900, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
//A
Date (const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
return *this;
}
//B
Date& operator=(const Date& d)
{
//防止进行自身赋值。如d1=d1这个情况
if(this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
private:
int _year ;
int _month ;
int _day ;
};
答案是B的写法更好,两种方法虽然都可以完成赋值运算符重载,但是在A中的写法在返回值的时候会调用拷贝构造,频繁的调用拷贝构造是存在效率问题的。