[C++]同じユーザ定義クラス間の比較について

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
zxc
記事: 79
登録日時: 11年前
住所: 日本の背骨(?)あたり

[C++]同じユーザ定義クラス間の比較について

#1

投稿記事 by zxc » 8年前

コード:

class math_vector2D{
 private:
  int x,y;
   //~省略~
 public:
  bool operator<(const math_vector2D&)const;
  bool operator==(const math_vector2D&)const;
  //~省略~
};
 上のようなクラスについて考えた時に、次のような比較を行ったとします。operator>(), operator>=(), operator<=()はoperator<()に実装を委譲すると基本的に考えることにします。

コード:

math_vector2D a = {1,2};
math_vector2D b = {2,1};
a<b; 
a<=b;
a==b;


 このとき、一般にどのような結果が与えられると期待される、またはどのような結果を与える実装をすべきなのでしょうか。
 とりあえず3パターン考え、個人的には1. に追加でIsSame関数等でコピーであるかようなオブジェクトかを判定するのが良いのかと思いましたが、どうなのでしょうか。

  1. operator<()を一方向ハッシュ値の比較などで実装し、operator==()はoperator<に実装を委譲
    →operator==()でtrueが得られてもオブジェクトの値が等しいとは限らない
  2. operator<()を優先順位を付ける等の方法で厳密に大小関係を決定する実装にし、operator==()はoperator<に実装を委譲
    →operator==()でtrueが得られれば2つのオブジェクトは等しい
    →しかし大小関係の優先順位は客観的とは言えないかもしれない
  3. operator<()を一方向ハッシュ値の比較などで実装し、operator==()はoperator<と独立に一方がもう一方のコピーであるかを判定するかのような実装にする
    →operator==でtrueが得られれば2つのオブジェクトは等しい
    →operator<=() は operator<() && operator==() と !(operator>() ) 両方とは等しくならないかもしれない?


具体例

1.実装例 → this->x==other.y && this->y == other.x でoperator==()はtrueになってしまう

コード:

bool math_vector2D::operator<(const math_vector2D& other)const{
    return this->x * this->y < other.x * other.y ;
}
bool math_vector2D::operator==(const math_vector2D& other)const{
    return ( ( *this < other)&&(other<*this) ); 
}
2.実装例 →直感的なメンバ変数間の優先順位だろうか?

コード:

bool math_vector2D::operator<(const math_vector2D& other)const{
    if( this->y == other.y ) {
        return this->x < other.x;
    }else{
        return this->y < other.y;
    }
}

bool math_vector2D::operator==(const math_vector2D& other)const{
    return ( ( *this < other)&&(other<*this) ); 
}
3.実装例 → a(1,2), b(2,1), c = a, d(3,3); のとき a<=bはどうなる?

コード:

bool math_vector2D::operator<(const math_vector2D& other)const{
    return this->x * this->y < other.x * other.y ;
}
bool math_vector2D::operator==(const math_vector2D& other)const{
    return ( ( this->x == other.x )&&( this->y == other.y ) ); 
}

3.の問題例(true, falseはあくまで予想です)

コード:

a(1,2), b(2,1), c = a, d(3,3);
a<b    //false ・・・(1)
b<a    //false ・・・(2) ( = a>b )
a==b  //false ・・・(3)
a==c  //true
b==c  //false
a<d    //true
b<d    //true

//このとき下の結果は・・・?
a<=b 
// operator>()から実装( 例えば !( operator>() )  ) →(2)から  !(false) = true
// operator<()とoperator==から実装( 例えば( operator<() && operator==() ) ) →(1)と(3)から ( false && false ) = false;

アバター
h2so5
副管理人
記事: 2212
登録日時: 13年前
住所: 東京
連絡を取る:

Re: [C++]同じユーザ定義クラス間の比較について

#2

投稿記事 by h2so5 » 8年前

大小関係の比較ができないクラスにoperator<を実装するのが根本的な間違いです。

zxc
記事: 79
登録日時: 11年前
住所: 日本の背骨(?)あたり

Re: [C++]同じユーザ定義クラス間の比較について

#3

投稿記事 by zxc » 8年前

コメントを頂いてからいろいろ考えた結果、比較すべきでないため比較演算子を実装すべきではないという結論に至りました。ありがとうございました。

閉鎖

“C言語何でも質問掲示板” へ戻る