简体   繁体   English

关于链接器和多个类声明的 C++ 问题

[英]C++ Question about linker and multiple class declarations

So I have a file called test.cpp所以我有一个名为 test.cpp 的文件

class Entity
{
    int c = 0;
    int b = 0;
    int d = 5;

};

And then another called main.cpp然后另一个叫做 main.cpp

#include<iostream>
#include<vector>
#include<algorithm>
class Entity
{

    int a = 5;
    int b = 0;


};
int main()
{
    
}

Why does this link and work just fine?为什么这个链接可以正常工作? Doesn't the linker see that there are 2 classes with the same name and different data members?链接器没有看到有 2 个具有相同名称和不同数据成员的类吗? Also would these be considered class definitions?这些也会被视为类定义吗? If I wanna declare this class in a header file I would just do what I did here right?如果我想在头文件中声明这个类,我会做我在这里做的事情吗? Even though I'm technically defining variables it's still just a class declaration right..?即使我在技术上定义了变量,它仍然只是一个类声明,对吧..?

It is an ill-formed program.这是一个格式错误的程序。

As the class definition has external linkage then each definition of the class shall consist of the same sequence of tokens.由于类定义具有外部链接,因此类的每个定义都应包含相同的标记序列。

On the other hand, as neither code from the translation unit test.cpp is used the linker can exclude it from the final exe file.另一方面,由于翻译单元 test.cpp 中的代码都没有使用,链接器可以将其从最终的 exe 文件中排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM