gpt4 book ai didi

c++ - 为内联函数定义多次,怎么可能?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:24 26 4
gpt4 key购买 nike

下面引自 C++ primer 书的引述让我很困惑

Unlike other function, inline and constexpr functions may be defined multiple times in the program. After all, the compiler needs the definition, not just the declaration, in order to expand the code. However, all of the definitions of a given inline or constexpr must match exactly. As a result, inline and constexpr functions normally are defined in headers. -- C++ primer 5th Ed, 240 pp

“可能在程序中多次定义” 这句话让我很困惑。据我了解,声明可以多次进行,但定义只需要一次。

谁能给我一个例子,为什么会有多个定义。

最佳答案

在一个头文件中(我们称之为foo.h)你可以有

inline int foo() { /* do stuff */ }

现在,如果您将 foo.h 包含在几个 cpp 文件中,那么 foo 将在每个文件中定义,这将是一个多重定义错误。尽管 foo 被标记为 inline,但没关系,因为所有定义都是相同的。

As far as I understand, declaration can be made multiple time, but definition is only needed once

编译器在翻译单元(基本上是一个 cpp 文件)上工作,它可以在其中进行各种优化,但函数内联和 constexpr 要求编译器知道函数的定义。这意味着每个翻译单元都需要其中的函数定义。我们使用 inline 来确保这一点,否则会出现多重定义错误。

关于c++ - 为内联函数定义多次,怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com