C / C ++ Struct与类 [英] C/C++ Struct vs Class

查看:108
本文介绍了C / C ++ Struct与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在完成我的C ++类后,结构/类几乎完全相同,除了一些细微的差别。

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

我从来没有在C中编程;但我知道它有结构。在C中是否可以继承其他结构并设置一个公共/私有的修饰符?

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 ++?在C ++中,结构和类是什么使得类与结构不同?

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

推荐答案

相同;唯一的区别是,在类中的访问修饰符(对于基类的成员变量,方法,),默认为private,struct中的访问修饰符默认为public。但是,在C 中,结构只是(公共)数据的聚合集合,没有其他类的特性:没有方法,没有构造函数,没有基类等。虽然C ++继承了关键字,它扩展了语义。 (这就是为什么在结构体中默认为public的原因 - 一个像C结构体一样的结构像一个结构体一样。)

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (edit: for member variables, methods, and for base classes) in classes default to private, access modifiers in structs default to public. 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&mdash中伪造一些OOP ;例如,定义所有指向struct作为其第一个参数的函数,或偶尔将具有相同前几个字段的struct强制为sub / superclasses,它总是有螺栓并且不是语言的真正部分。

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 ++ Struct与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆