我有一个类 Dimension
我在 Dimension.h 文件中定义(就像我的所有类一样):
class Dimension
{
public:
constexpr Dimension() noexcept;
constexpr Dimension(int w, int h) noexcept;
int width;
int height;
};
我认为我可以像在我所有的类(class)中一样,将定义放在单独的 Dimension.cpp 中:
#include "Dimension.h"
constexpr Dimension::Dimension() noexcept : width(0), height(0) {}
constexpr Dimension::Dimension(int w, int h) noexcept : width(w), height(h) {}
但是当我尝试使用该类时,编译器告诉我:
警告:内联函数 'constexpr Dimension::Dimension()
' 已使用但从未定义
在链接时:
对'pong::graphics::Dimension::Dimension()
'的 undefined reference
(与其他构造函数相同)
如果我像这样在标题中定义类:
class Dimension
{
public:
constexpr Dimension() noexcept : width(0), height(0) {}
constexpr Dimension(int w, int h) noexcept : width(w), height(h) {}
int width;
int height;
};
省略 .cpp 文件,一切正常。
我使用的是 GCC 4.9.2。为什么单独定义不起作用?
最佳答案
如果 constexpr
函数未在头文件中定义,则编译器在编译所有其他源文件时无法看到 constexpr
函数的定义。
显然,如果它看不到函数的定义,它就无法在编译时执行计算它们所需的步骤。因此,所有 constexpr
函数都必须在使用它们的任何地方定义。
感谢@IgorTandetnik:
[dcl.constexpr] §7.1.5/2
constexpr
functions andconstexpr
constructors are implicitly inline.
[basic.def.odr] §3.2/4
An inline function shall be defined in every translation unit in which it is odr-used.
关于c++ - 是否可以在 header 中声明 constexpr 类并将其定义在单独的 .cpp 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27345284/