在C+&#x2B中的布尔上下文中,在布尔上下文中使用户定义的类型为真/错误。
我有一个line
,代表笛卡尔平面上一条线的相关信息。具有bool
的类型,该类型指示是否定义了斜率。我希望能够执行以下操作:
if(my_line){
double new_slope = my_line.slope * 9;
}
在布尔上下文中,实例my_line
本身被隐式转换为true/false值。我正在考虑使用智能指针看到的行为,如果指向nullptr
或0
,则该实例被视为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的
line
类中,实现bool
转换操作员。您还可以选择超载operator!
但这在C ++ 11及以后不需要。参见上下文转换。例如:
In your
Line
class, implement abool
conversion operator. You could also optionally overload theoperator!
, but that is not required in C++11 and later. See Contextual conversions.For example: