c++ - C++ 重载布尔运算符
问题描述
我是重载运算符的新手。我正在尝试重载布尔运算符。我目前正在使用 bool 运算符作为 Date 类的访问函数。有什么建议我将如何将 bool EqualTo 函数转换为重载运算符?谢谢!
class Date {
private:
int mn; //month component of a date
int dy; //day component of a date
int yr; //year comonent of a date
public:
//constructors
Date() : mn(0), dy(0), yr(0)
{}
Date(int m, int d, int y) : mn(m), dy(d), yr(y)
{}
//access functions
int getDay() const
{
return dy;
}
int getMonth() const
{
return mn;
}
int getYear() const
{
return yr;
}
bool EqualTo(Date d) const;
};
bool Date::EqualTo(Date d) const
{
return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}
解决方案
您的函数的实现EqualTo
表明您应该重载operator==
以测试 2 个Date
对象是否相等。您所要做的就是重命名EqualTo
为operator==
. 你应该通过const&
.
bool Date::operator==(Date const &d) const
{
return (mn == d.mn) && (dy == d.dy) && (yr == d.yr);
}
在 class 内部Date
,声明如下所示:
bool operator==(Date const &d) const;
另一种方法是让操作符成为类的朋友:
friend bool operator==(Date const &a, Date const &b) const
{
return (a.mn == b.mn) && (a.dy == b.dy) && (a.yr == b.yr);
}
请注意,在这种情况下,这不是成员函数。在这种情况下,您可以在类中定义它(您需要friend关键字)。
如果你friend
在类外定义了一个函数,你仍然需要friend
在类内声明它。但是,定义不能再有friend
关键字。
我还建议您更清楚地命名变量,例如month
,day
和year
.
推荐阅读
- html - 无法增加图像大小以扩展到父级之外
- javascript - 井字游戏正则表达式
- apache-spark - 与看似等效的 PySpark 转换实现不同的结果
- smtp - DNN SendGrid 配置不起作用
- python - 初学者问题:RASP PI 4 - Python - IOError
- vue.js - 带有方法的Vue样式
- pine-script - 如何组合振荡器协同工作?
- kubernetes - 如何在 kubernetes 的同一节点中为一项服务(同一 pod 的多个实例)联系一个随机 pod
- node.js - RabbitmQ Producer & Consumer 的设计建议
- c# - C#记录构造函数参数默认值空IEnumerable