問題描述
在完成我的 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++ 結構與類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!