C/C++ 结构与类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2750270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:35:35  来源:igfitidea点击:

C/C++ Struct vs Class

c++classstruct

提问by Antal Spector-Zabusky

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

完成我的 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 中是否可以继承其他结构并设置 public/private 的修饰符?

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

如果您可以在常规 C 中做到这一点,为什么我们还需要 C++?是什么使类与结构不同?

回答by Antal Spector-Zabusky

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++ 中,结构和类几乎相同;唯一的区别是类中的访问修饰符(用于成员变量、方法和基类)默认为 private,结构中的访问修饰符默认为 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 中,结构体只是(公共)数据的聚合集合,并没有其他类似类的特性:没有方法、没有构造函数、没有基类等。虽然 C++ 继承了关键字,但它扩展了语义。(然而,这就是为什么结构体默认为 public 的原因——像 C 结构体一样编写的结构体的行为就像一个结构体。)

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 occasionallycoercing 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 中伪造一些 OOP——例如,定义所有将指向结构的指针作为它们的第一个参数的函数,或者偶尔将具有相同前几个字段的结构强制为“子/超类”——但它总是有点用螺栓固定,并且实际上并不是语言的一部分。

回答by Lance Diduck

Other that the differences in the default access (public/private), there is no difference.

除了默认访问(公共/私有)的差异之外,没有区别。

However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."

但是,一些使用 C 和 C++ 编码的商店将使用“类/结构”来表示哪些可以在 C 和 C++ 中使用(结构),哪些只能在 C++ 中使用(类)。换句话说,在这种风格中,所有结构都必须使用 C 和 C++。这就是为什么很久以前就存在差异的原因,当时 C++ 还被称为“C with Classes”。

Note that C unions work with C++, but not the other way around. For example

请注意,C 联合适用于 C++,但反之则不然。例如

union WorksWithCppOnly{
    WorksWithCppOnly():a(0){}
    friend class FloatAccessor;
    int a;
private:
    float b;
};

And likewise

同样

typedef union friend{
    int a;
    float b;
} class;

only works in C

仅适用于 C

回答by Dave

I'm going to add to the existing answers because modern C++is now a thing and official Core Guidelineshave been created to help with questions such as these.

我将添加到现有答案中,因为现代 C++现在已经成为一种东西,并且已经创建了官方核心指南来帮助解决诸如此类的问题。

Here's a relevant section from the guidelines:

以下是指南中的相关部分:

C.2: Use class if the class has an invariant; use struct if the data members can vary independently

An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume. After the invariant is established (typically by a constructor) every member function can be called for the object. An invariant can be stated informally (e.g., in a comment) or more formally using Expects.

If all data members can vary independently of each other, no invariant is possible.

If a class has any private data, a user cannot completely initialize an object without the use of a constructor. Hence, the class definer will provide a constructor and must specify its meaning. This effectively means the definer need to define an invariant.

Enforcement

Look for structs with all data private and classes with public members.

C.2:如果类有不变量,则使用类;如果数据成员可以独立变化,则使用 struct

不变量是对象成员的逻辑条件,构造函数必须为公共成员函数建立该条件。在建立不变量后(通常由构造函数),可以为对象调用每个成员函数。可以非正式地(例如,在评论中)或更正式地使用 Expects 来陈述不变量。

如果所有数据成员可以相互独立地变化,则不可能有不变性。

如果一个类有任何私有数据,如果不使用构造函数,用户就不能完全初始化一个对象。因此,类定义器将提供一个构造函数并且必须指定其含义。这实际上意味着定义者需要定义一个不变量。

执法

查找具有所有数据私有的结构和具有公共成员的类。

The code examples given:

给出的代码示例:

struct Pair {  // the members can vary independently
    string name;
    int volume;
};

// but

class Date {
public:
    // validate that {yy, mm, dd} is a valid date and initialize
    Date(int yy, Month mm, char dd);
    // ...
private:
    int y;
    Month m;
    char d;    // day
};

Classes work well for members that are, for example, derived from each other or interrelated. They can also help with sanity checking upon instantiation. Structs work well for having "bags of data", where nothing special is really going on but the members logically make sense being grouped together.

Class例如,es 非常适用于相互派生或相互关联的成员。它们还可以帮助在实例化时进行完整性检查。Structs 非常适合拥有“数据包”,其中没有什么特别的事情发生,但成员在逻辑上被分组在一起是有意义的。

From this, it makes sense that classes exist to support encapsulation and other related coding concepts, that structs are simply not very useful for.

由此看来,classes 的存在是为了支持封装和其他相关的编码概念,而structs对它并没有多大用处。

回答by Johannes Schaub - litb

It's not possible to define member functions or derive structs from each other in C.

不可能在 C 中定义成员函数或从彼此派生结构。

Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.

此外,C++ 不仅是 C + 的“派生结构”。C 中不存在模板、引用、用户定义的命名空间和运算符重载。

回答by MarsRover

One more difference in C++, when you inherit a class from struct without any access specifier, it become public inheritance where as in case of class it's private inheritance.

C++ 中的另一个区别是,当您从 struct 继承一个类而没有任何访问说明符时,它成为公共继承,而在类的情况下,它是私有继承。

回答by Chris Hafey

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

C++ 使用结构主要是为了 1) 向后兼容 C 和 2) POD 类型。C 结构体没有方法、继承或可见性。