C++ 比较两个对象并使用运算符返回true(如果它们正常)
我尝试比较两个对象,如果它们匹配,则使用运算符返回true,但没有运气。请帮助输入此代码。我试过用p.date extra,但没用 类名为C++ 比较两个对象并使用运算符返回true(如果它们正常),c++,comparison,operator-keyword,C++,Comparison,Operator Keyword,我尝试比较两个对象,如果它们匹配,则使用运算符返回true,但没有运气。请帮助输入此代码。我试过用p.date extra,但没用 类名为DateC bool DateC::operator-=(const DateC& p) const { // if() {return true;}; // return true; }; assert( d -= DateC(1, 2, 2001) ); 假设您确实需要-=操作员,潜在客户可能是: const DateC &
DateC
bool DateC::operator-=(const DateC& p) const
{
// if() {return true;};
// return true;
};
assert( d -= DateC(1, 2, 2001) );
假设您确实需要
-=
操作员,潜在客户可能是:
const DateC & DateC::operator -= ( const DateC& rhs) {
this->day = ?; // do something with rhs.day
this->month = ?; // do something with rhs.month
this->year = ?; // do something with rhs.year
return *this;
}
但是根据您问题的标题,您正在寻找=
操作员:
另一条线索:
bool DateC::operator == ( const DateC &rhs ) const {
if ((this->day != rhs.day) ||
(this->month != rhs.month) ||
(this->year != rhs.year)) {
return false;
}
return true;
}
按如下方式使用:
bool ok = (DateC(1,2,2001) == DateC(11,2,2001)); // Returns false
注意:当然,您可以用
-=
替换我的==
,但对于任何想使用它的人来说,这都有点扭曲。很抱歉,这不起作用,我只想比较对象p和datec(),如果两者相等,则返回true。在我提供的实现中,我真的不明白。你想比较两个日期。比如:boolok=(DateC(1,22001)==DateC(11,22001))
。这就是我的第二个主张(rhs
是你的p
)。。。自己试试看(或者不要使用操作符)。