这是我关于函数声明和定义的知识。如果有什么不对的地方请指正。
// 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
andconstexpr
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; }
当您编译这些文件时,函数 foo
和 bar
会在 file1.cpp 的目标代码以及 file2.cpp 的目标代码中定义。当您链接这些目标代码以创建可执行文件时,foo
和 bar
各有两个定义。这是合法的。
但是,不允许在同一编译单元中对同一个 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/