三元运算符(?:)是if-else语句的一种简洁语法糖,它可以让简单的条件判断更加简洁和易读。
三元运算符的语法格式:条件 ? 值1 : 值2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
static int s_Level = 1;
static int s_Speed = 2;
int main()
{
// 传统的if-else写法
if (s_Level > 5)
s_Speed = 10;
else
s_Speed = 5;
// 使用三元运算符的简洁写法
s_Speed = s_Level > 5 ? 10 : 5;
std::cout << s_Speed << std::endl;
}
|
1
2
3
4
5
6
7
8
9
10
11
|
int main()
{
int score = 85;
// 根据分数判断等级
std::string grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" : "D";
std::cout << "Grade: " << grade << std::endl;
}
|
1
2
3
4
5
6
7
8
9
10
|
void PrintMessage(bool isError)
{
std::cout << (isError ? "Error: " : "Info: ") << "Operation completed" << std::endl;
}
int main()
{
PrintMessage(true); // 输出: Error: Operation completed
PrintMessage(false); // 输出: Info: Operation completed
}
|
1
2
3
4
5
6
7
8
9
|
int GetMax(int a, int b)
{
return a > b ? a : b;
}
int GetAbsolute(int value)
{
return value < 0 ? -value : value;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <vector>
int main()
{
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 安全访问数组元素
int index = 10;
int value = index < numbers.size() ? numbers[index] : -1;
std::cout << "Value: " << value << std::endl; // 输出: Value: -1
}
|
虽然可以嵌套使用,但要注意可读性:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
int main()
{
int temperature = 25;
// 嵌套三元运算符
std::string weather = temperature > 30 ? "Hot" :
temperature > 20 ? "Warm" :
temperature > 10 ? "Cool" : "Cold";
std::cout << "Weather: " << weather << std::endl;
// 对于复杂逻辑,建议使用if-else
std::string recommendation;
if (temperature > 30) {
recommendation = "Stay indoors with AC";
} else if (temperature > 20) {
recommendation = "Perfect for outdoor activities";
} else if (temperature > 10) {
recommendation = "Wear a light jacket";
} else {
recommendation = "Bundle up!";
}
}
|
三元运算符的两个分支必须能够转换为同一类型:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
int main()
{
bool condition = true;
// 正确:两个分支都是int类型
int result1 = condition ? 10 : 20;
// 正确:可以隐式转换为同一类型
double result2 = condition ? 10 : 20.5; // int可以转换为double
// 正确:都可以转换为string
std::string result3 = condition ? "Hello" : std::string("World");
// 注意:确保类型兼容
auto result4 = condition ? 10 : 20.5; // result4的类型是double
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
int Add(int a, int b) { return a + b; }
int Multiply(int a, int b) { return a * b; }
int main()
{
bool useAdd = true;
// 选择不同的函数
auto operation = useAdd ? Add : Multiply;
int result = operation(5, 3);
std::cout << "Result: " << result << std::endl; // 输出: Result: 8
}
|
- 简单的条件赋值
- 短小的条件表达式
- 函数参数中的简单选择
- 复杂的嵌套逻辑
- 条件或结果表达式很长
- 需要执行多个语句的情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 好的使用方式
int max = a > b ? a : b;
std::string status = isOnline ? "Online" : "Offline";
// 不推荐的使用方式(太复杂)
int result = (a > b && c < d) ? (x * y + z) : (calculateComplexValue(a, b, c));
// 应该改为if-else
int result;
if (a > b && c < d) {
result = x * y + z;
} else {
result = calculateComplexValue(a, b, c);
}
|
- 三元运算符是if-else的一种简洁语法糖,适用于简单的条件判断
- 语法格式:
条件 ? 值1 : 值2
- 适用场景:简单的条件赋值、函数参数选择、返回值选择
- 注意事项:两个分支的类型必须兼容,避免过度嵌套影响可读性