本文介绍了用于错误检查的转换功能好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想有一个简单的方法来检查对象是否有效。我想到一个简单的转换函数,像这样:I'd like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this: operator bool() const { return is_valid; }检查它是否有效会很简单Checking for it to be valid would be very simple now// is my object invalid?if (!my_object) std::cerr << "my_object isn't valid" << std::endl;这是否被视为良好做法? Is this considered a good practise? 推荐答案在C ++ 03中,您需要使用 safe bool idiom 避免邪恶的事情:In C++03, you need to use the safe bool idiom to avoid evil things:int x = my_object; // this works在C ++ 11中,您可以使用显式转换:In C++11 you can use an explicit conversion:explicit operator bool() const{ // verify if valid return is_valid;}这种方式需要明确转换为bool,不再偶然的做疯狂的事情(在C + +你可以永远做的疯狂的事情的目的):This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):int x = my_object; // does not compile because there's no explicit conversionbool y = bool(my_object); // an explicit conversion does the trick > if 和 while 需要一个布尔表达式,因为这些语句的条件是上下文转换为bool: This still works as normal in places like if and while that require a boolean expression, because the condition of those statements is contextually converted to bool:// this uses the explicit conversion "implicitly"if (my_object){ ...}这在§ : 表达式 e 可以隐含转换为 T 如果且仅当声明 T t = e; 形式良好,用于一些发明的临时变量 t (§ 8.5)。某些语言结构需要将表达式转换为布尔值。出现在这样的上下文中的表达式 e 被认为是上下文地转换为 bool 且格式良好当且仅当声明 bool t(e); 形式良好时, $ b发明的临时变量 t (&Sect; 8.5)。 隐式转换的效果与执行声明和初始化相同,然后使用临时变量作为转换结果。 An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (§8.5). Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (§8.5). The effect of either implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.(有什么区别是使用 bool t(e); 而不是 bool )(What makes the difference is the use of bool t(e); instead of bool t = e;.)这些上下文转换为bool的地方包括:The places were this contextual conversion to bool happens are: 的条件如果, while 和 语句; $ ,逻辑结合 &&&&&&< / code>和逻辑结果 || ; 条件运算符?:; 条件 static_assert ; noexcept 异常说明符的可选常量表达式; the conditions of if, while, and for statements;the operators of logical negation !, logical conjunction &&, and logical disjunction ||;the conditional operator ?:;the condition of static_assert;the optional constant expression of the noexcept exception specifier; 这篇关于用于错误检查的转换功能好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 07:59