LoginSignup
2
0

More than 3 years have passed since last update.

C++でクラスのbool演算子をオーバーロードする

Last updated at Posted at 2020-07-19

(2020/07/20訂正:×オーバーライド、○オーバーロード。およびoperator boolにexplicit)

はじめに

RealSenseのサンプルコードを見ていて、掲題のようなことが出来るという勉強ができたので自前のサンプルコードを書いて確認してみました。元ネタのコード(コレ、とコレ)ではウィンドウクラスのオブジェクトを見ながらwhileループを回して、ウィンドウが閉じた際にfalseを返して終了処理、という感じでした。

何をするか

クラスのメンバでboolをoperatorでオーバーロードしてifやwhileの条件文でクラスオブジェクトが参照できるようにする、というものです。

テストコード

こんなコードで確認しました。(2020/07/20訂正:operator boolにexplicit)

#include <iostream>

class TestClass {
    int max;
    int count;
public:
    TestClass(int max) {
        this->max = max;
        count = 0;
    }

    ~TestClass() = default;

    // explicitを付けて暗黙的な変換を防止(2020/07/20訂正分)
    explicit operator bool() {
        bool retVal = false;

        if (count >= max) {
            retVal = true;
        }
        count++;

        return retVal;
    }
};

int main()
{
    // explicitしているので、operator <<で暗黙的キャストされず
    // コンパイルエラーにできる(2020/07/20訂正分)
    //TestClass test0(0);
    //std::cout << test0 << std::endl;

    TestClass test(3);

    while (!test)
    {
        std::cout << "counting." << std::endl;
    }
    std::cout << "count end." << std::endl;
}

クラスのメンバにoperator boolを加えてwhileの条件文でオブジェクトを参照することwhile(!test)で真偽処理が動きます。

2
0
2

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
0