混淆了具有相同名称的类的结构
confused about struct an class with same name
我正在复习一些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.cpp
和test2.cpp
的对象文件链接在一起,则foo
将有两个冲突的定义。因此,该程序将违反一个定义规则,并且格式不正确。
您看到的是来自classtest.h
的class foo
,而不是来自test2.cpp
的。在C++中,除了默认成员访问(struct,
私有for
类的public
)之外,class
和struct
之间没有区别。
这就是为什么在foo
的实例中有成员b
。代码编译和链接良好的原因是没有同时定义两个foo
。每个翻译单元只定义一个。
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?