【问题标题】:comparing 2 objects and returning true if they ok using operator比较 2 个对象,如果它们可以使用运算符返回 true
【发布时间】:2013-06-16 23:51:36
【问题描述】:

我正在尝试比较 2 个对象,如果它们匹配则返回 true,但没有运气。请帮助使用此代码。我尝试过使用 p.date extra 但它不起作用

类名是DateC

bool DateC::operator-=(const DateC& p) const
{
    // if() {return true;};
    // return true;
};
assert( d -= DateC(1, 2, 2001) );

【问题讨论】:

    标签: c++ comparison operator-keyword


    【解决方案1】:

    假设您真的想要 -= 运算符,则潜在客户将是:

    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。所有在我提供的实现中
    • 我真的不明白。您想比较两个日期。喜欢:bool ok = (DateC(1,2,2001) == DateC(11,2,2001))。这就是我提出的第二个提议(rhs 是你的p)...自己试试看(或者不要使用运算符)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2012-11-03
    • 2021-04-06
    相关资源
    最近更新 更多