混淆了具有相同名称的类的结构

confused about struct an class with same name

本文关键字:结构      更新时间:2023-10-16

我正在复习一些c++代码,遇到了一个我不理解的问题。我有多个cpp文件,一个main.cpp带有:

#include <iostream>
#include "classtest.h"
#include "test2.h"
using namespace std;
int main() {
foo test;
test.b=5;
...

看看includes,test2.h是空的,而test2.cpp只包含以下内容:

struct foo{
    int a;
};

包含的另一个标头classtest.h包含以下内容:

using namespace std;
class foo{
public:
    int a;
    int b;
};

正如您所看到的,有一个类和结构具有相同的名称。我的问题是:为什么我的主方法中的类型foo是结构而不是类?标头test2.h中没有定义,main如何访问它?第二个问题:给定foo是结构体(我使用eclipse,看到它将鼠标光标放在上面),如何访问结构体不存在的字段b?对不起,我对c++还很陌生,我需要澄清这个疑问。非常感谢。

除了#include <iostream>之外,如果手动替换#include s,则最终会将其替换为main.cpp:

#include <iostream>
using namespace std;
class foo{
public:
    int a;
    int b;
};
using namespace std;
int main() {
foo test;
test.b=5;

由此可见,CCD_ 13就是CCD_ 14。这里一点也不可疑。

为什么我的主方法中的类型foo是结构而不是类?

test2.cpp中定义的不是foo。您包含了来自classtest.h的定义,因此这就是main中使用的定义。

它没有在头test2.h中定义,main如何访问它?

它没有,也不能访问未包含的定义。

第二个问题:给定的foo是结构

这个前提是错误的。

如何访问结构中不存在的字段b?

因为,正如我们得出的结论,foo是在classtest.h中定义的。


请注意,如果将main.cpptest2.cpp的对象文件链接在一起,则foo将有两个冲突的定义。因此,该程序将违反一个定义规则,并且格式不正确。

您看到的是来自classtest.hclass foo,而不是来自test2.cpp的。在C++中,除了默认成员访问(struct,私有for类的public)之外,classstruct之间没有区别。

这就是为什么在foo的实例中有成员b。代码编译和链接良好的原因是没有同时定义两个foo。每个翻译单元只定义一个。