C++-无法在三元运算符内部调用内联std::cerr



我正在尝试制作一个非常简单的setter方法,在设置之前检查start值是否不高于end值。

这是基本代码:

if (start <= this->end) {
this->start = start;
} else {
cerr << "Start cannot be higher than end." << endl;
}

我试着通过使用内联if语句来简化这个方法,比如:

(start <= this->end) ? (this->start = start) : (cerr << "Start cannot be higher than end." << endl);

但IntelliSense告诉我以下问题:function "std::basic_ostream<_Elem, _Traits>::basic_ostream(const std::basic_ostream<_Elem, _Traits> &) [with _Elem=char, _Traits=std::char_traits<char>]" cannot be referenced -- it is a deleted function

嗯,我有点困惑于什么";删除的函数";必须将一个简单的if语句转换为内联语句。可能需要一些帮助。谢谢

三元条件表达式a ? b : c表达式,因此不等价于if (a) { b } else { c }

因为它是一个表达式,所以它必须有一个类型(如果该类型不是void,它也有一个值(。这就是为什么可以将三元条件放在赋值的右侧(在某些情况下甚至放在左侧(。

条件表达式的类型由其第二和第三操作数的类型确定。如果它们具有相同的类型,那么结果就是该类型。如果没有一些";毫不含糊的";类型,则三元表达式不会默认为void结果;它反而会导致编译错误。

在您的情况下,两个操作数是:

  • (this->start = start)
  • (cerr << "Start cannot be higher than end." << endl)

我认为前者具有某种数字类型(this->start类型(,而后者具有std::ostream&类型。不存在规范的";普通型";在这两种类型中,或者换句话说,三元运算符没有"0";明显的";结果类型,并且发生编译错误。

if语句可以解决这个问题。如果你坚持使用条件运算符,你可以这样做:

(start <= this->end)
? void(this->start = start)
: void(cerr << "Start cannot be higher than end." << endl);

这里,第二和第三表达式都被强制转换为void,因此整个三元表达式具有结果类型void

请注意,不能将类似breakreturn的内容作为操作数之一。condition ? void(return foo) : void(return bar)将不起作用,因为return <expr>语句,而不是表达式。它没有类型,甚至连void都没有。在这种情况下,您只能使用if语句。但是,您可以在条件表达式中使用throw,因为throw <expr>是一个表达式。

true大小写和false大小写的语句类型必须匹配。

尝试将, this->start(逗号运算符,然后是this->start(添加到false大小写中以匹配类型:

(start <= this->end) ? (this->start = start) : (cerr << "Start cannot be higher than end." << endl, this->start);

顺便说一句,我的建议是,如果你想在一行中写东西,你应该简单地在一行写if语句,而不是像这样使用条件运算符:

if (start <= this->end) this->start = start; else cerr << "Start cannot be higher than end." << endl;

最新更新