如果我有一个头文件,我想在其中声明一个类:
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/