在 C++ 中使用条件运算符

本文将解释如何使用 C++ 条件运算符。

在 C++ 中使用条件运算符作为 rvalue 表达式

除了常见的算术、逻辑和赋值运算符之外,C++ 还提供了一些特殊的运算符,其中之一是条件三元运算符。三元意味着运算符采用三个操作数。它被称为条件运算符,因为它的工作方式类似于 if-else 语句。运算符的形式为 E1 ? E2 : E3,其中第一个操作数可以被视为 if 条件,它被评估并转换为 bool 值。

如果 bool 值为 true,则计算以下表达式 (E2),并产生副作用。否则,将评估第三个表达式 (E3) 及其副作用。请注意,我们可以使用此运算符作为 rvalue 表达式来有条件地为变量赋值。在下面的示例代码中,我们从用户输入中读取一个整数并计算比较表达式 input > 10,表示条件运算符中的 E1 操作数。仅当 E1 为真时,变量 n 才被赋予 input 值。

#include <string>#include <iostream>using std::cout; using std::endl;
using std::string; using std::cin;
int main() {
    int input;
    cout << "Enter a single integer: ";
    cin >> input;
    int n = input > 10 ? input : 10;
    cout << "n = " << n << endl;
    return EXIT_SUCCESS;
}

输出:

Enter a single integer: 21
n = 21

在 C++ 中使用条件运算符作为 lvalue 表达式

或者,我们可以使用三元运算符作为 lvalue 表达式来有条件地选择进行赋值操作的变量名称。请注意,我们仅将变量名称指定为第二个和第三个操作数。但是,通常你可以指定诸如 cout 之类的表达式,它具有外部副作用;这些效应会像往常一样被执行。

#include <string>#include <iostream>using std::cout; using std::endl;
using std::string; using std::cin;
int main() {
    int input;
    cout << "Enter a single integer: ";
    cin >> input;
    int n = input > 10 ? input : 10;
    cout << "n = " << n << endl;
    int m = 30;
    (n == m ? n : m) = (m * 10) + 2;
    cout << "m = " << m << endl;
    return EXIT_SUCCESS;
}

输出:

Enter a single integer: 21
n = 21
m = 302

三元运算符的另一个用例可以在 class 定义中。下面的代码示例演示了这样一个场景,我们为类似于单链表中的节点的 MyClass 结构实现了一个递归构造函数。在这种情况下,我们将构造函数调用指定为第二个操作数,使用 next 参数调用,并继续递归调用堆栈,直到 node.next 评估为 false 值。后者仅适用于 node.next 指针为 nullptr 的情况。

#include <string>#include <iostream>struct MyClass {
    MyClass* next;
    int data;
    MyClass(const MyClass& node)
            : next(node.next ? new MyClass(*node.next) : nullptr), data(node.data) {}
    MyClass(int d) : next(nullptr), data(d) {}
    ~MyClass() { delete next ; }
};
int main() {
    return EXIT_SUCCESS;
}