如果我们想要类能和内置函数一样能比较大小怎么办
比如
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year, int month, int day)
{
this->year = year;
this->_month = month;
this->_day = day;
}
private:
int year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 5, 18);
Date d2(2021,5,16);
if (d1 < d2)
{
cout << "小于" << endl;
}
else
{
cout << "大于" << endl;
}
return 0;
}
这个代码其实是编译不过的,它不像内置类型一样能编译过,为什么?
因为内置类型是系统自己定义的,而自定义类型不同,因为这是自己定义,因为是自己定义的,所以系统没办法进行运算
那么编译器为了支持自定义类型可以使用各种运算符,所以就出了运算符重载
但是不要认为和函数重载是相同的,函数重载是函数名相同,参数不同,而运算符重载要解决的就是让自定义类型使用运算符
赋值运算符重载使用规则
函数原型:返回值类型 operator操作符(参数列表)
参数是运算符操作数
返回值是运算符运算后结果
使用演示
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
//private:
int _year;
int _month;
int _day;
};
bool operator==(Date& d1, Date& d2)
{
return d1._year==d2._year
&&d1._month==d2._month
&&d1._day==d2._day;
}
int main()
{
Date d1(2022, 5, 18);
Date d2(2022,5,18);
if (operator==(d1, d2))
{
cout << "==" << endl;
}
return 0;
}
运行结果
看代码其实知道这代码是有点问题的,因为year这些成员变量是私有的所以不变成公有是编译不过去
但是是公有的话,那些我就没有办法有私有变量
那么怎么保证成员变量是私有的,我还能调用它
答案是类里面,不过因为写在类外面和类里面是有不同的,所以二个都讲
1.为什么要用operator==而不是定义成一个函数
在看完代码过后给一种感觉这不就是函数的调用吗?我不用operator==用成函数名不好吗?因为这是告许你可以这样用,但是这不是他真正的用法
可以看到这里把他重载了过后,能直接使用这个函数
其实这里就是编译器做了处理相当于
if (d1==d2)//(operator==(d1, d2))
{
cout << "==" << endl;
}
编译器会寻找它有没有重载,如果有重载就替换,如果没有就报错
2.赋值运算符重载在类里面使用
正确的使用方式
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2022, 5, 18);
Date d2(2022,5,18);
if (d1.operator==(d2))
{
cout << "==" << endl;
}
if (d1 == d2)
{
cout << "==" << endl;
}
return 0;
}
bool operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
上面函数为什么只调用一个参数,是因为阴藏的this指针,如果上面写二个参数那总共加起来就是三个参数了
为什么加引用,因为不加上引用就会调用拷贝构造函数了
来个好玩的,下面代码会编译错误吗?如果没有调用的是那个函数
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
bool operator==(Date d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
//private:
int _year;
int _month;
int _day;
};
bool operator==(const Date& d1,const Date& d2)
{
return d1._year == d2._year
&& d1._month == d2._month
&& d1._day == d2._day;
}
int main()
{
Date d1(2022, 5, 18);
Date d2