[英]Programming principles and practice using C++ error: constexpr
In Stroustrup's "Programming principles and practice" book, there's an example of constexpr
like this:在 Stroustrup 的“编程原理和实践”一书中,有一个这样的constexpr
示例:
void user(Point p1)
{
Point p2 {10,10};
Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine
constexpr Point p4 = scale(p2); // p4 == {100,8}
constexpr Point p5 = scale(p1); // error: scale (p1) is not a constant
// expression
constexpr Point p6 = scale(p2); // p6 == {100,8}
// . . .
}
p2
although initialized with constant expression arguments (literals here 10, 10) it is not a constexpr
object because it is not declared so.但认为他弄错了: p2
虽然用常量表达式 arguments(这里的字面量为 10、10)初始化,但它不是constexpr
object,因为它没有这样声明。 So normally p4
and p6
are in error here: (cannot use p2
in a constant expression).所以通常p4
和p6
在这里是错误的:(不能在常量表达式中使用p2
)。 it is like p1
.就像p1
。
To correct it:要纠正它:
constexpr Point p2{10, 10};
You know who is really good at telling you if something is allowed as a constexpr
?你知道谁真正擅长告诉你某事是否被允许作为constexpr
吗? Your compiler.你的编译器。 https://godbolt.org/z/4Kdocx83v https://godbolt.org/z/4Kdocx83v
And you are right, it's broken.你是对的,它坏了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.