c++ - inline 或 constexpr 函数的多个定义的含义

标签 c++ function declaration definition

这是我关于函数声明和定义的知识。如果有什么不对的地方请指正。

// Function Declaration
// This is usually put in .h header file
int occur (const char* sentence, const char& achar);

// Function Definition
// This is usually put in .cpp
int occur (const char* sentence, const char& achar) { // do job and return }

我正在阅读《C++ Primer 第五版》。在“inline 和 constexpr 函数@ Chapter 6.5.2 P.240”下,它说

Unlike other functions, inline and constexpr functions may be defined multiple times in the program.

我脑子里想出了这样的东西:

// function delcaration .h file
constexpr int returnfour();

// function definition in .cpp file
constexpr int returnfour () { return 4; }
constexpr int returnfour () { return 4; }

像这样有多个定义是否正确? 在程序中多次定义是什么意思?什么时候有人想要这样做?

最佳答案

Unlike other functions, inline and constexpr functions may be defined multiple times in the program.

假设你有一个:

inline int foo() { return 10; }
constexpr int bar() { return 20; }

现在,您将该文件#include 到几个.cpp 文件中。

文件1.cpp:

#include "a.h"

// ... other functions

文件2.cpp:

#include "a.h"

// ... other functions

int main() { return 0; }

当您编译这些文件时,函数 foobar 会在 file1.cpp 的目标代码以及 file2.cpp 的目标代码中定义。当您链接这些目标代码以创建可执行文件时,foobar 各有两个定义。这是合法的。

但是,不允许在同一编译单元中对同一个 inline 函数或 constexpr 函数进行多个定义。

使用:

inline int foo() { return 10; }
inline int foo() { return 10; }

constexpr int bar() { return 20; }
constexpr int bar() { return 20; }

在单个 cpp 文件中是不合法的。

关于c++ - inline 或 constexpr 函数的多个定义的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34835430/

相关文章:

c++ - CMake 在 build 和 src 目录之间拆分生成的文件

javascript - 我可以在 JavaScript 的原型(prototype)函数中使用私有(private)方法吗?

Python 无法在函数中定义元组

c++ - c++ 函数签名的语法规范(关键字/上下文关键字顺序)是什么?

c++ - C++ 模板中的名称查找

c++ - "map/set iterators incompatible" map 销毁,取决于构造函数调用

function - 如何将多个文本字段合并为一个 IBACTION? - swift

Java 初学者 : initializing class variables

c - 在C中,如果我只是声明一个变量而不初始化它,编译器会为其保留空间吗?

angular - Typescript 自定义接口(interface)变量声明