在Stroustrup的例子中,冒号在"return 1 : 2"中是什么意思?
In Stroustrup's example, what does the colon mean in "return 1 : 2"?
我不明白冒号的一种特殊用法。
我在Bjarne Stroustrup的The C++ Programming Language一书中找到了它,第4版,第11.4.4节"Call and Return",第297页:
void g(double y)
{
[&]{ f(y); } // return type is void
auto z1 = [=](int x){ return x+y; } // return type is double
auto z2 = [=,y]{ if (y) return 1; else return 2; } // error: body too complicated
// for return type deduction
auto z3 =[y]() { return 1 : 2; } // return type is int
auto z4 = [=,y]()−>int { if (y) return 1; else return 2; } // OK: explicit return type
}
令人困惑的冒号出现在语句 return 1 : 2
的第 7 行。我不知道会是什么。它不是标签或三元运算符。
它看起来像一个没有第一个成员(也没有?
(的条件三元运算符,但在这种情况下,我不明白它如何在没有条件的情况下工作。
这是书中的一个错字。查看勘误表,了解 The C++ Programming Language 的第 2 次和第 3 次打印。示例必须如下所示:
auto z3 =[y]() { return (y) ? 1 : 2; }
在我看来
就像一个简单的错字。应该是:
auto z3 =[y]() { return y ? 1 : 2; }
请注意,由于 lambda 不带任何参数,因此括号是可选的。如果您愿意,可以改用它:
auto z3 =[y] { return y ? 1 : 2; }
return 1 : 2;
是语法错误,它不是有效的代码。
正确的陈述更像是return (y) ? 1 : 2;
。
相关文章:
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 线应该是什么意思
- "CID"在AT+HTTPPARA= "CID" ,1中是什么意思
- 表达式"b=(b-x)&x"是什么意思?
- 这个表达是什么意思?
- 此代码验证公式是什么意思?
- 跟踪日志中的T.11803()是什么意思?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- _T("xyz")是什么意思?
- #define Dbg(fmt,..) (0) 是什么意思? 警告:表达式无效
- 这行代码到底是什么意思?
- 当我们说在执行程序时将操作系统的控制权传递给main()函数时,我们的意思是什么
- 这句话在c++中的意思是什么
- 这个typedef的意思是什么
- 这句话的意思是什么
- 意思是什么
- 这个句法的意思是什么?