C++:在多个文件中定义 class

C++: Defining class in multiple files

根据One Definition Rule (ODR)

In the entire program, an object or non-inline function cannot have more than one definition; if an object or function is used, it must have exactly one definition.

这些是我正在尝试编译的文件:

A.cpp

#include <iostream>
#include "Greet.h"

int main()
{
    greet();
    std::cin.get();
}

B.cpp

#include "Greet.h"

Greet.h

#include <iostream>

void greet()
{
    std::cout << "Hello World!" << std::endl;
}

我收到预期的链接器错误:

fatal error LNK1169: one or more multiply defined symbols found.

但是当我将 greet() 函数放在 class 中时。代码编译正常并给出输出 Hello World!.

A.cpp

#include <iostream>
#include "Greet.h"

int main()
{
    Greet G;
    G.greet();

    std::cin.get();
}

B.cpp

#include "Greet.h"

Greet.h

#include <iostream>

class Greet
{
public:
    void greet()
    {
        std::cout << "Hello World!" << std::endl;
    }
};

为什么链接器不抱怨 class Greet 的多个定义?

MSVC 和 g++ 的行为相同。

But when I put greet() function in a class. The code compiles fine and gives the output Hello World!.

当在 class 定义中定义成员函数时,隐含 inline。 non-member 函数并非如此。

来自C++ Standard, class.mfct

A member function may be defined ([dcl.fct.def]) in its class definition, in which case it is an inline member function ([dcl.fct.spec]), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.