C++条件运算符的使用

Use of Conditional Operator in C++

下面的代码给出了一个编译器错误:--> rough.cpp:6:30: error: operands to ?: have different types 'short int' and 'const char*'

int main() {
    for (short i {10}; i <= 100; i += 10) {
        cout<<((i % 15 == 0) ? i : "-")<<endl;
    }
    return 0;
}

此代码编译无任何错误或警告:

int main() {
    for (short i {10}; i <= 100; i += 10) {
        cout<<((i % 15 == 0) ? i : '-')<<endl; // error line
    }
    return 0;
}

并显示以下输出:

    45
    45
    30
    45
    45
    60
    45
    45
    90
    45

谁能解释一下这是怎么回事,两者之间有什么区别?

因为我希望预期的输出是:

-
-
30
-
-
60
-
-
90
-

条件运算符的操作数必须是同一类型或可转换为某些通用类型。 cppreference 上有一长串关于此的规则,但这里发生的是 ishort int 正在转换为 char。此外,intchar const* 没有共同的类型,因此会出错。

您希望 i 打印为字符串。

((i % 15 == 0) ? to_string(i) : "-")

操作数必须具有相同的类型或共同的 type:

If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)

在您的第一个示例中,您有一个 string(const char*),它与 ​​int 没有共同的类型。

虽然在第二个示例中您有一个 char,但可以将其转换为 int

有时最好的解决方案是最简单的解决方案。在这种情况下,您不能使用三元运算符 ?: 因为您没有相同的 return 类型。因为你的第一个 return 是一个整数,所以你的其他 '-' 也变成了一个整数。

int main() {
    for (short i {10}; i <= 100; i += 10) {
        if(i % 15 == 0)
        {
            cout << i << endl;
        }
        else
        {
            cout << '-' << endl;
        }
    }
    return 0;
}