如何为代理类实现相等操作符函数
How to implement an equality operator function for a proxy class
我定义了一个类Date来建模一个日期,它有一个日、一个月和一个年作为数据成员。现在为了比较日期,我创建了相等运算符
bool Date::operator==(const Date&rhs)
{
return (rhs.day()==_day && _month==rhs.month() &&_year==rhs.year());
}
现在我如何从代理类调用日期类相等操作符…??
这是问题的编辑部分
这是日期类
//Main Date Class
enum Month
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
class Date
{
public:
//Default Constructor
Date();
// return the day of the month
int day() const
{return _day;}
// return the month of the year
Month month() const
{return static_cast<Month>(_month);}
// return the year
int year() const
{return _year;}
bool Date::operator==(const Date&rhs)
{
return (rhs.day()==_day && _month==rhs.month() &&_year==rhs.year());
}
~Date();
private:
int _day;
int _month;
int _year;
}
//--END OF DATE main class
这是我要替换Date类的代理类
//--Proxy Class for Date Class
class DateProxy
{
public:
//Default Constructor
DateProxy():_datePtr(new Date)
{}
// return the day of the month
int day() const
{return _datePtr->day();}
// return the month of the year
Month month() const
{return static_cast<Month>(_datePtr->month());}
// return the year
int year() const
{return _datePtr->year();}
bool DateProxy::operator==(DateProxy&rhs)
{
//what do I return here??
}
~DateProxy();
private:
scoped_ptr<Date> _datePtr;
}
//--End of Proxy Class(for Date Class)
现在我遇到的问题是在代理类中实现相等运算符函数,我希望这能澄清问题。
那就用运算符:
Date d1, d2;
if(d1 == d2)
// ...
注意operator==
是如何接受引用的。这意味着,如果你有一个指针(或一个像指针一样的对象,如scoped_ptr
或shared_ptr
),那么你必须首先取消对它的引用:
*_datePtr == *rhs._datePtr;
顺便说一下,你应该读一下:操作符重载
return *_datePtr == *_rhs.datePtr;
如果正确实现,它应该像任何其他相等操作符一样工作。
试题:
Date a = //date construction;
Data b = //date construction;
if(a == b)
printf("a and b are equivalent");
else
printf("a and b are not equivalent");
相关文章:
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- 当delete操作符释放内存时,我为什么需要析构函数
- 为什么操作符的新函数需要强制转换
- 如何使操作符的左操作数<<一个函数
- 如何重载操作符==外模板类使用友元函数
- 在泛型函数中没有匹配操作符==
- Assert()函数抛出一个错误——操作符有问题
- 删除操作符,它们等同于c++中的析构函数
- 复制构造函数,赋值操作符重载
- 强制转换操作符函数在g++中可以很好地编译,但在其他编译器中不行.为什么
- 通过调用Move赋值操作符实现Move构造函数
- 在类赋值操作符函数中,为什么必须返回*this ?
- 有没有一种方法可以通过函数指针来调用操作符函数?
- 如何为代理类实现相等操作符函数
- 如何为嵌套类编写范围解析操作符函数头
- 类不能包含内部定义枚举的操作符函数
- 从结构指针调用重载操作符函数
- 操作符函数和与之相关的编译错误
- 带有指向对象指针的操作符函数
- 复制和交换技术在赋值操作符函数内部使用复制构造函数