2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++で構造体の比較演算子に関するエラーの解決方法

Last updated at Posted at 2024-06-27

エラー内容

C++で整数をひとつ持つ構造体 MyStruct と比較演算子 operator== を定義しました.

struct MyStruct{
    int val;

    MyStruct(int val) : val(val) {}

    bool operator == (const MyStruct& rhs) {
        return val == rhs.val;
    }
};

int main() {
    std::pair<MyStruct, MyStruct> a(10, 20), b(10, 20);

    // pairの比較
    std::cout << (a == b) << std::endl;

    return 0;
}

std::pair<MyStruct, MyStruct> の比較を行うと,以下のエラーが発生しました.

error: no match for ‘operator==’ (operand types are ‘const MyStruct’ and ‘const MyStruct’)
  641 |     { return __x.first == __y.first && __x.second == __y.second; }

解決方法

このエラーは,比較演算子が const 修飾されていないことが原因です.比較演算子を以下のように修正することでエラーを解決できます.

bool operator == (const MyStruct& rhs) const {
    return val == rhs.val;
}

エラー原因

std::pair の比較では,要素の比較時に const なオブジェクトを使うため,比較演算子に const メソッドが必要になります.const メソッドとして定義することで,const なオブジェクト同士の比較が可能になります.

const メソッドとは

const をメソッドに付けることで,その関数がオブジェクトの値を変更しないことを保証します.

特に,const オブジェクトから呼び出すことができます.const でないメソッドは const オブジェクトから呼び出すことができません.

これが今回の原因で,std::pair では const オブジェクトを用いているため,比較時に非 const メソッドの operator== を呼び出せなかったということです.

friend 関数として定義

friend bool operator == (const MyStruct& lhs, const MyStruct& rhs) {
    return lhs.val == rhs.val;
}

このように friend 関数として定義しても動作します.

friend 関数とは

特定のクラスの非メンバ関数でありながら,そのクラスのプライベートメンバにアクセスできる関数です.

今回の例なら,グローバルに operator== をオーバーロードして,MyStruct を引数に取り,MyStruct のメンバにアクセスしています.

今回は valpublic ですが,valprivate であってもこの関数は動作します.

最後に

競技プログラミング用の modint 構造体で pair を用いた時にエラーが出ており,解決に時間がかかったので書きました.

間違いや補足等ありましたらご連絡ください.

参考

https://cpprefjp.github.io/reference/utility/pair.html
https://learn.microsoft.com/ja-jp/cpp/cpp/friend-cpp?view=msvc-170
https://wisdom.sakura.ne.jp/programming/cpp/cpp24.html
https://wisdom.sakura.ne.jp/programming/cpp/cpp28.html

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?