运算符定义不正常

时间:2013-06-16 22:53:38

标签: c++

我正在尝试实现比较运算符,但我收到以下错误

  

whole.cpp(384):错误C2270:'==':非成员函数不允许使用修饰符
  whole.cpp(384):错误C2805:二进制'运算符=='参数太少了   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()

1 个答案:

答案 0 :(得分:0)

您可以将比较运算符实现为成员函数或自由函数。要将其作为自由函数实现,您需要接受两个参数 - =左侧的值和=右侧的值。以下示例显示了如何正确执行此操作。

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引用,以允许使用rvalues(临时值)。

相关问题