c++ - 链接器如何将头文件声明变成定义?

标签 c++

如果我有一个头文件,我想在其中声明一个类:

class Entity
{
 int a;
 int b;
 void do_something();

};

那这只是一个普通的声明,对吧?

class Entity
{
 int a = 0;
 int b;
 void do_something();

};

但是现在这会把它变成一个定义吗?如果是这样,当我尝试将该头文件包含到两个 .cpp 文件中时究竟会发生什么?我基本上将在两个文件中定义两个实体类,但这可以吗?如果没问题,那为什么没问题?链接器究竟要做什么?

最佳答案

Then this is just a normal declaration right?

class Entity
{
 int a = 0;
 int b;
 void do_something();

};

没有。这是 Entity 类的定义,其中包括 do_something() 方法的声明。

I'm basically gonna have two Entity classes defined in two files but is this okay? And if it is okay why is it okay?

这没关系,因为单一定义规则允许在多个翻译单元中重新定义类,只要定义相同即可。

您可以将其视为具有隐式 inline 的所有类定义。

关于c++ - 链接器如何将头文件声明变成定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69810345/

相关文章:

c++ - 为什么我们可以使用 SFINAE 检测 operator() 的默认参数值的存在,但不能检测自由函数和 PMF 的默认参数值?

c++ - 链接到 Boost 预编译库时获取 LnK1104

c++ - 寻找高级 C++ SSL 库

c++ - 是否可以在已经具有主要功能的 cpp 文件上运行测试?

c++ - qTreeView scrollToBottom() 忽略

C++ 头文件(基础)

c++ - CPython 是字节码解释器吗?

c++ - CLR C++ VS C++ (pstsdk)

c++ - 如何将对象插入STL集

c++ - OpenCV 球面投影 : Warping and Unwarping