Assert()函数抛出一个错误——操作符有问题

assert() function throwing an error something wrong with the operator

本文关键字:错误 有问题 一个 操作符 函数 Assert      更新时间:2023-10-16

我得到的错误是

whole.cpp(384): error C2270: '==' : modifiers not allowed on nonmember functions
whole.cpp(384): error C2805: binary 'operator ==' has too few parameters
whole.cpp(384): error C2274: 'function-style cast' : illegal as right side of '.' operator

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

是类中的操作符实现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()

当您创建自己的类时,如果您想比较它们,则需要为它们创建操作符。假设您想比较一个类Person的两个实例。

一个人由字符串和int型(姓和高)组成。

我们希望通过身高来比较人们,所以我们需要告诉编译器如何做。一个例子:

class Person
{
    string lastname;
    int height;
    bool operator == (const Person& p) const
    {
        return (this->height == p.height);
    }
};
编辑:

我想你误解了我的例子,你只能比较编译器知道如何比较的东西。你的Date实现可能有整型,所以如果你要检查是否相等,你必须检查所有字段。

使用this->来访问函数中其他对象的字段