C++ 重载bool类型

在C++中,可以通过重载operator bool()来实现对自定义类型的bool类型重载。这样,您可以定义自定义类型的对象在条件语句中的行为,使其能够像内置类型一样进行条件判断。

下面是一个示例,演示了如何在C++中重载bool类型:

#include <iostream>
#include <string>
using namespace std;

class Test {
private:
    bool isNonEmpty;
public:
    Test(const string& str) {
        isNonEmpty = !str.empty();
    }

    // 重载 operator bool(),使得 Test 类型的对象可以在条件语句中进行判断
    explicit operator bool() const {
        return isNonEmpty;
    }
};

int main() {
    Test t1("Hello");
    Test t2("");

    if (t1) {
        cout << "t1 is non-empty" << endl;
    } else {
        cout << "t1 is empty" << endl;
    }

    if (t2) {
        cout << "t2 is non-empty" << endl;
    } else {
        cout << "t2 is empty" << endl;
    }

    return 0;
}

在上面的示例中,我们定义了一个Test类,并重载了operator bool()使得Test类型的对象可以在条件语句中进行判断
explicit关键字用于防止隐式类型转换,确保只有显式调用时才会进行类型转换。

posted @ 2024-01-16 16:54  guanyubo  阅读(80)  评论(0编辑  收藏  举报