简体   繁体   English

有没有办法声明将使用 constexpr 在源文件中定义的公共 static const (有什么区别)?

[英]Is there a way to declare a public static const that will be defined in the source file using constexpr (and what difference is there)?

In my header I have a public static const declared and I define in the source file as a class member.在我的 header 中,我声明了一个公共 static 常量,并在源文件中将其定义为 class 成员。 I want to define it in the source file because I am including and using a constant from an it, and I don't want to include in my header.我想在源文件中定义它,因为我包含并使用它的常量,并且我不想包含在我的 header 中。

If I use static constexpr in the header it requires a definition there.如果我在 header 中使用 static constexpr 它需要在那里定义。

header header

public:
  static const double DEG_TO_RADIANS;

source资源

#include <math.h>

const double MyClass::DEG_TO_RADIANS = (M_PI/180.0);

Is this a situation where you just can't use constexpr, does this matter at all?这是您不能使用 constexpr 的情况吗,这有关系吗?

Why does a static const allow me to not define the variable but static constexpr doesn't?为什么 static const 允许我不定义变量但 static constexpr 不允许?

Edit: The M_PI is a simple example of this situation.编辑: M_PI 是这种情况的一个简单示例。

The whole point of constexpr is to use it for values that can be known at compile time. constexpr的全部意义在于将它用于在编译时可以知道的值。 That doesn't work if the definition is in a completely different file.如果定义在完全不同的文件中,那将不起作用。

Static const requires you to provide a definition which a linker can connect between different files. Static const 要求您提供 linker 可以在不同文件之间连接的定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM