在C+&#x2B中的布尔上下文中,在布尔上下文中使用户定义的类型为真/错误。

发布于 2025-01-25 02:39:42 字数 338 浏览 2 评论 0原文

我有一个line,代表笛卡尔平面上一条线的相关信息。具有bool的类型,该类型指示是否定义了斜率。我希望能够执行以下操作:

if(my_line){
   double new_slope = my_line.slope * 9;
}

在布尔上下文中,实例my_line本身被隐式转换为true/false值。我正在考虑使用智能指针看到的行为,如果指向nullptr0,则该实例被视为false as-is。

我将如何模仿这种行为?

I have a Line that represents the relevant information of a line on the cartesian plane. The type that has, among other members, a bool that indicates whether the slope is defined. I would like to be able to do the following:

if(my_line){
   double new_slope = my_line.slope * 9;
}

where the instance my_line itself is implicitly converted to a true/false value in a boolean context. I am thinking of the behavior I see with smart pointers, where if it is pointing to nullptr or 0, the instance is considered false as-is.

How would I go about emulating this behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说谎友 2025-02-01 02:39:42

在您的line类中,实现bool转换操作员。您还可以选择超载 operator! 但这在C ++ 11及以后不需要。参见上下文转换

例如:

class Line {
    bool mSlopeDefined;
    ...

public:
    ...

    explicit operator bool() const noexcept {
        return mSlopeDefined;
    }

    // optional since C++11, but doesn't hurt...
    bool operator!() const {
        return !mSlopeDefined;
    }
};

In your Line class, implement a bool conversion operator. You could also optionally overload the operator!, but that is not required in C++11 and later. See Contextual conversions.

For example:

class Line {
    bool mSlopeDefined;
    ...

public:
    ...

    explicit operator bool() const noexcept {
        return mSlopeDefined;
    }

    // optional since C++11, but doesn't hurt...
    bool operator!() const {
        return !mSlopeDefined;
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文