C/C++ 结构与类

C/C++ Struct vs Class(C/C++ 结构与类)
本文介绍了C/C++ 结构与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在完成我的 C++ 课程后,在我看来,结构/类几乎完全相同,只有一些细微的差异.

After finishing my C++ class it seemed to me the structs/classes are virtually identical except with a few minor differences.

我以前从未用 C 编程过;但我知道它有结构.在C中是否可以继承其他结构并设置public/private的修饰符?

I've never programmed in C before; but I do know that it has structs. In C is it possible to inherit other structs and set a modifier of public/private?

如果您可以在常规 C 中执行此操作,为什么我们还需要 C++?什么使类与结构不同?

If you can do this in regular C why in the world do we need C++? What makes classes different from a struct?

推荐答案

在 C++ 中,结构和类几乎相同;唯一的区别是类中的访问修饰符(用于成员变量、方法和基类)默认为 private,而结构中的访问修饰符默认为 public.

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

然而,在 C 中,结构体只是(公共)数据的聚合集合,没有其他类似类的特性:没有方法、没有构造函数、没有基类等.虽然C++继承了关键字,扩展了语义.(然而,这就是为什么结构体默认为 public 的原因——像 C 结构体一样编写的结构体的行为也很相似.)

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

虽然可以在 C 中伪造一些 OOP—例如,定义函数,这些函数都将指向结构的指针作为它们的第一个参数,或者偶尔强制结构具有相同的前几个字段子类/超类"——它总是被附加的,并不是语言的真正组成部分.

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

这篇关于C/C++ 结构与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)