【发布时间】:2015-03-04 01:37:56
【问题描述】:
我必须使用 if 语句检查 3 种方法的结果。如果method1为真,那么我只需要调用method2,如果method2为真,那么我只需要调用method3。目前我正在为此目的使用以下代码。
if(method1())
{
if(method2())
{
if(method3())
{
cout << "succeeded";
}
else
{
cout << "failed";
}
}
else
{
cout << "failed";
}
}
else
{
cout << "failed";
}
我只想使用一个 if 语句并在其中调用所有 3 个方法。所以我正在考虑以下方式。下面的代码和上面的代码是一样的还是会有所不同?
if(method1() && method2() && method3())
{
cout << "succeeded";
}
else
{
cout << "failed";
}
【问题讨论】:
-
是的,
&&使用短路(假设method不返回operator &&重载的对象)。
标签: c++ if-statement short-circuiting