-3

私が得ているエラーは

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()

4

1 に答える 1

3

独自のクラスを作成するときにそれらを比較したい場合は、それらの演算子を作成する必要があります。クラス Person の 2 つのインスタンスを比較したいとします。

person は、string と int (名字と身長) で構成されます。

人々を身長で比較したいので、コンパイラーにその方法を伝える必要があります。例:

class Person
{
    string lastname;
    int height;

    bool operator == (const Person& p) const
    {
        return (this->height == p.height);
    }

};

編集:

私の例を誤解していると思います。コンパイラが比較方法を知っているものしか比較できません。Date の実装にはおそらく int があるため、等しいかどうかをチェックする場合は、すべてのフィールドをチェックする必要があります。

this->関数内の他のオブジェクトのフィールドにアクセスするために使用します。

于 2013-06-16T21:03:13.460 に答える