c++ - 是否可以在 header 中声明 constexpr 类并将其定义在单独的 .cpp 文件中?

标签 c++ c++11 constexpr

我有一个类 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 and constexpr 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/

相关文章:

c++ - 如何在 C++ 中添加延迟

c++ - MPL 序列 : is this legal? 的用户定义文字

c++ - 模板推导指南可以调用 constexpr 函数吗?

c++ - constexpr、数组和初始化

c# - 文本差异应用程序如何工作?

c++ - OpenGL 3.x/4x 中的纹素/像素匹配

c++ - 是否可以创建一个 C 文件对象以在内存中读/写

c++ - 具有来自不同对象的函数的函数数组

c++ - 成员模板的别名模板

c++ - 从 std::vector 获取特定结构对象的快速方法