gpt4 book ai didi

c++ - 我的以下断言是否正确?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:51:08 26 4
gpt4 key购买 nike

在他的新书“TCPL”的第 10.4.3 节中,B. Stroustrup 写道:

A sufficiently simple user-defined type can be used in a constant expression. For example:

struct Point {
int x,y,z;
constexpr Point up(int d) { return {x,y,z+d}; }
constexpr Point move(int dx, int dy) { return {x+dx,y+dy}; }
// ...
};

A class with a constexpr constructor is called a literal type. To be simple enough to be constexpr, a constructor must have an empty body and all members must be initialized by potentially constant expressions. For example:

constexpr Point origo {0,0};

这让我感到困惑,原因如下:

  • struct Point 没有用户定义的构造函数,其隐式默认构造函数也不是 constexpr。
  • constexpr Point origo {0,0}; 根据标准 (N3337) 中关于在对象声明中使用 constexpr 的第 7.1.5/9 段进行编译和第 8.5.1/7 段,关于聚合初始化。它与 constexpr 构造函数无关。

最佳答案

不需要用户定义的构造函数。文中说“用户定义的类型”,这是真的,“构造函数必须有一个空体”,这是真的(默认构造函数等同于一个空体)。

constexpr 也用于表示结果是一个编译时常量。它不允许/禁止函数上的任何特定语法,它只允许编译器在编译时验证是否按预期返回常量值。函数和声明中的 constexpr 仅表示函数返回编译时常量。

编辑:哦,另外,我认为您可能会在该引用中链接一些独立的陈述。第一句话和代码片段说明了如何将用户定义类型 Point 用作 constexpr 函数的返回值。第二位说明 Point 可以用作 constexpr 变量,因为它的构造函数是空的; {0,0} 语法本身与 constexpr constructors 没有特别相关,但它满足 constexpr 变量,其中“构造函数必须有一个空体,所有成员必须由潜在的常量表达式初始化”。参见 here了解与 constexpr 一起使用的变量/函数/构造函数术语。

关于c++ - 我的以下断言是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com