运算符定义不能正常工作

operator definition not working right

本文关键字:工作 常工作 定义 不能 运算符      更新时间:2023-10-16

我试图实现一个比较运算符,但我得到以下错误

whole.cpp(384):错误C2270: '==':非成员函数不允许修饰符
whole.cpp(384):错误C2805:二进制'operator =='参数太少
whole.cpp(384):错误C2274: 'function-style cast':非法的'。"操作符

我似乎无法确定问题所在,所以这里是代码

这是类

中的操作符实现
bool operator==(const DateC& p) const
{
    return ( DateC::DateC()== p.DateC() );
};
#include <assert.h>
int main(unsigned int argc, char* argv[])
{
    DateC f(29,33,11);
    DateC::testAdvancesWrap();
};
void DateC::testAdvancesWrap(void)
{
    DateC d;
    cout << "DateC::testAdvanceWrap()" << endl ;
    cout << "*********************" << endl << endl ;
    cout << "tCHECK ADVANCE MULTIPLES:" << endl;
    cout << "t------------------------" << endl;
    d.setDay(1);
    d.setMonth(12);
    d.setYear(1999); 
    prettyPrint(d);
    cout << "ACTION: set date 01-Dec-1999, advance, 31 days, 1 month and 1 year ->" << endl;
    d.advance(1,1,31);
    assert( d == DateC(1,2,2001) );
    cout << "SUCCESS" << endl;
    prettyPrint(d);
    cout << endl << endl;
}

其他的函数工作得很好,只有assert()

可以将比较运算符实现为成员函数或自由函数。为了实现它作为一个自由函数,你需要接受两个参数——左边的=的值和右边的=的值。下面的例子展示了如何正确地做到这一点。

struct Date
{
    int variable_;
};
bool operator==(const Date& lhs, const Date& rhs)
{
    return lhs.variable_ == rhs.variable_;
}

要将比较运算符实现为成员函数,只需要接受一个实参,即=右边的值。拥有正在执行的比较运算符的对象是=左侧的值。在这种情况下,操作符应该是const限定的。

struct Date
{
    int variable_;
    bool operator==(const Date& rhs) const
    {
        return variable_ == rhs.variable_;
    }
};

在任何情况下,参数都应该作为const引用,以允许使用右值(临时值)。