处理两个if条件的最简单方法
Simplest way to handle two if conditions
这与之前的问题相同,但我在描述问题时犯了很多错误。所以我再试一次。请原谅我的用词。这可能是错的。我是编程新手。
我有两个指针指向对象(我想)A和B。它们看起来像这样:
Class1* A = Blah->Method1();
Class2* B = A->Method2();
我必须在执行一些代码之前检查这些是否存在。以下是条件:
- A和B同时存在:执行Action1和Action2
- 存在,且其中一个为空:只执行Action1
- 均为空:只执行Action1
这是我到目前为止的代码:
if (A){
/*some code here. B is created here */
if (B){
// Perform action1. Action1 always comes before Action2
// Perform action2
}
}
else{
//Perform action1
}
这适用于4个案例中的3个。当A存在但B为空时,它会失败。
我该如何改进?(如果可能的话,同时将//Perform Action 1
保持在最里面的if中。其他建议也欢迎。)
谢谢。
- A和B同时存在:执行Action1和Action2
- 存在,且其中一个为空:只执行Action1
- 均为空:只执行Action1
所以,真的,你想:
action1();
if (a && b) {
action2();
}
你的标准总是涉及调用action1
;没有理由用if
来保护它。如果同时找到a
和b
,则调用action2
。
这个比上次清楚多了。这使得解决方案很简单:
bool doAction2 = false;
if (A) {
/*some code here. B is created here */
doAction2 = (B != null);
}
action1();
if (doAction2) {
action2();
}
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 请求最简单的 OpenMP 目标 GPU 示例
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- 对多个(可能)重叠范围进行分区的最简单算法
- 在 cpp 中最简单的图形实现
- boost::variant - 对变体应用算术的最简单方法
- 多线程 gtkmm 应用程序最简单的示例
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- 标准库容器最简单、性能差的哈希类是什么?
- 哪种条件最能容忍良好做法?
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 无法获得最简单的JNI足以在Windows 10上运行
- 从 txt 文件中读取数据的最简单方法
- QThread:用最简单的代码竞态条件
- 处理两个if条件的最简单方法