例如:
operator bool() const
{
return col != 0;
}col是一个整数。operator bool() const是如何工作的?
发布于 2011-01-05 10:25:03
表单的成员函数
operator TypeName()是转换运算符。它们允许使用类类型的对象,就像它们是TypeName类型的对象一样,当它们是类型时,使用转换函数将它们转换为TypeName。
在这种情况下,operator bool()允许使用类类型的对象,就好像它是一个bool一样。例如,如果您有一个名为obj的类类型的对象,则可以将其用作
if (obj)这将调用operator bool(),返回结果,并将结果用作if的条件。
应该注意的是,operator bool()是一个非常糟糕的想法,你真的不应该使用它。有关它不好的原因以及问题的解决方案的详细解释,请参阅"The Safe Bool Idiom."
(即将推出的C++标准修订版C++0x增加了对显式转换运算符的支持。这些将允许您编写一个正确工作的安全explicit operator bool(),而不必跳过实现安全布尔惯用法的繁琐步骤。)
发布于 2011-01-05 10:28:36
operator bool() const
{
return col != 0;
}定义如何将类转换为布尔值,()之后的const用于指示此方法不会发生变化(更改此类的成员)。
您通常会按如下方式使用运算符:
airplaysdk sdkInstance;
if (sdkInstance) {
std::cout << "Instance is active" << std::endl;
} else {
std::cout << "Instance is in-active error!" << std::endl;
}发布于 2016-08-20 20:10:08
为了清楚起见,我想给出更多的代码。
struct A
{
operator bool() const { return true; }
};
struct B
{
explicit operator bool() const { return true; }
};
int main()
{
A a1;
if (a1) cout << "true" << endl; // OK: A::operator bool()
bool na1 = a1; // OK: copy-initialization selects A::operator bool()
bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization
B b1;
if (b1) cout << "true" << endl; // OK: B::operator bool()
// bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}https://stackoverflow.com/questions/4600295
复制相似问题