#include <iostream>
using namespace std;
class MyClass {
private:
int price;
public:
explicit MyClass(int priceParam) : price(priceParam) {}
int CompareTo(const MyClass& a) const {
if( price == a.price )
return 0;
else if( price < a.price )
return -1;
else
return 1;
}
#define CMP(Class) \
bool operator < (const Class& that) const { return CompareTo(that) < 0; } \
bool operator > (const Class& that) const { return CompareTo(that) > 0; } \
bool operator == (const Class& that) const { return CompareTo(that) == 0; } \
bool operator <= (const Class& that) const { return CompareTo(that) <= 0; } \
bool operator >= (const Class& that) const { return CompareTo(that) >= 0; } \
bool operator != (const Class& that) const { return CompareTo(that) != 0; }
CMP(MyClass);
};
int main() {
MyClass A(32),B(60),C(32);
if( A == C )
cout << "A == C" << endl;
if( B > A )
cout << "B > A." << endl;
if( A < B )
cout << "A < B." << endl;
if( A != B )
cout << "A != B." << endl;
}
木曜日, 7月 18, 2013
自作クラスの比較オペレータを効率的に定義する方法
以下のアイデアはSafe C++で紹介されている.
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿