简体   繁体   English

使用C++编程原理与实践报错:constexpr

[英]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}
    // . . .
}
  • But think he is mistaken: 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).所以通常p4p6在这里是错误的:(不能在常量表达式中使用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.

相关问题 使用C ++的编程原理和实践第4章练习1 - Programming Principles and Practice using c++ chapter 4 drill 1 使用C ++的编程原理和实践第4章钻取,第7步 - Programming Principles and Practice Using C++ Chapter 4 Drill, Step 7 无法链接来自使用c ++的编程原理和实践的示例 - can not link examples from programming principles and practice using c++ 对于迭代,使用C ++对“编程原理和实践”进行“尝试此练习”练习 - 'Try This' exercise on Programming Principles and Practice Using C++, For iteration 编程:C ++的原理和实践-Cout问题 - Programming: principles and practice in c++ - cout issue 使用 C++ 的原则和实践中来自头文件的错误消息 - Error message from header file in Principles and Practice using C++ “使用C ++的原理和实践”章节6.3.1代码错误? - “Principles and Practice Using C++” chapter 6.3.1 code error? 在“编程:使用C ++的原理和实践”(第4章)的第7章中使用“ cin”获得7号钻的不同结果 - Getting different results using “cin” for Drill #7 in Chapter 4 of Programming: Principles and Practice using C++ (Stroustrup) 我正在尝试从书中做一个练习:编程——使用 C++ 的原则和实践(第二版) - I'm trying to do an exercise from the book :Programming -- Principles and Practice Using C++ (Second Edition) 编程:原理与实践使用C ++第4章钻取第6步:关于数值范围的一般问题 - Programming: Principles and Practice Using C++ chapter 4 drill step 6 : General question about numeric range
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM