我有一个类Dimension
,像我所有的类一样,我在文件 Dimension.h 中定义它:
class Dimension
{
public:
constexpr Dimension() noexcept;
constexpr Dimension(int w, int h) noexcept;
int width;
int height;
};
我原本以为可以像我所有的课程一样,将定义放在单独的 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()
'的未定义引用
(另一个构造函数同样如此)
如果我像这样在头文件中定义这个类:
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
函数的核心目的是允许在编译时计算函数。如果编译器看不到该函数的主体内容,则很难实现这一点。因此,需要让编译器看到整个函数的主体内容。 - Igor Tandetnikconstexpr
时完全展开,以便插入正确的表达式。链接阶段太晚了。 - πάντα ῥεῖconstexpr
函数和constexpr
构造函数隐式地是内联的。 3.2/4 内联函数应该在每个使用其 odr 的翻译单元中进行定义。 - Igor Tandetnik