在 C++ 中什么时候应该使用类还是结构?

发布于 2024-07-05 03:59:14 字数 70 浏览 5 评论 0原文

在什么情况下,在 C++ 中使用 struct 与使用 class 更好?

In what scenarios is it better to use a struct vs a class in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

羁客 2024-07-12 03:59:15

class 相比,struct 的一个优点是,如果遵循“先是公共成员,然后是私有成员”,它可以节省一行代码。 从这个角度来看,我发现关键字class毫无用处。

这是仅使用 struct 而从不使用 class 的另一个原因。 C++ 的一些代码风格指南建议对函数宏使用小写字母,理由是当宏转换为内联函数时,不需要更改名称。 同样在这里。 您拥有漂亮的 C 风格结构,有一天,您发现需要添加一个构造函数或一些便捷方法。 您是否将其更改为? 到处?

区分structclass对于我们应该做的事情——编程来说实在是太麻烦了。 与 C++ 的许多问题一样,它是出于对向后兼容性的强烈渴望而产生的。

An advantage of struct over class is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keyword class useless.

Here is another reason for using only struct and never class. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to a class? Everywhere?

Distinguishing between structs and classes is just too much hassle getting into the way of doing what we should be doing - programming. Like so many of C++'s problems it arises out of the strong desire for backwards compatibility.

ㄖ落Θ余辉 2024-07-12 03:59:15

structclass 在底层是相同的,尽管在可见性方面具有不同的默认值,struct 默认是 public,而 class 默认是私有的。 您可以通过适当使用 privatepublic 将其中一个更改为另一个。 它们都允许继承、方法、构造函数、析构函数以及面向对象语言的所有其他优点。

然而,两者之间的一个巨大区别是,C 中支持 struct 作为关键字,而 class 则不支持。 这意味着可以在包含文件中使用 struct,只要该 struct 是一个即可 #include 到 C++ 或 C 中纯 C 风格 struct 以及包含文件中的所有其他内容都与 C 兼容,即没有 C++ 特定关键字,例如 privatepublic,没有方法 。

AC 风格struct 可以与支持使用C 风格struct 在接口上来回传输数据的其他接口一起使用

AC 风格的 struct 是一种描述内存区域布局的模板(不是 C++ 模板,而是模式或模板)。 多年来,已经创建了可通过 C 语言和 C 插件(这里介绍的是 Java、Python 和 Visual Basic)使用的接口,其中一些接口可与 C 风格的 struct 配合使用。

Both struct and class are the same under the hood though with different defaults as to visibility, struct default is public and class default is private. You can change either one to be the other with the appropriate use of private and public. They both allow inheritance, methods, constructors, destructors, and all the rest of the goodies of an object oriented language.

However one huge difference between the two is that struct as a keyword is supported in C whereas class is not. This means that one can use a struct in an include file that can be #include into either C++ or C so long as the struct is a plain C style struct and everything else in the include file is compatible with C, i.e. no C++ specific keywords such as private, public, no methods, no inheritance, etc. etc. etc.

A C style struct can be used with other interfaces which support using C style struct to carry data back and forth over the interface.

A C style struct is a kind of template (not a C++ template but rather a pattern or stencil) that describes the layout of a memory area. Over the years interfaces usable from C and with C plug-ins (here's looking at you Java and Python and Visual Basic) have been created some of which work with C style struct.

把梦留给海 2024-07-12 03:59:15

正如其他人指出的那样,

  • 除了默认可见性之外,两者都是等效的,
  • 无论出于何种原因,可能都有理由被迫使用其中之一。Stroustrup

/Sutter 对于何时使用其中一个有明确的建议:

如果类具有不变量则使用类; 如果数据成员可以独立变化,则使用结构

但是,请记住,转发声明某物是不明智的。 作为类 (class X;) 并将其定义为结构 (struct X { ... })。
它可能在某些链接器(例如,g++)上工作,但在其他链接器(例如,MSVC)上可能会失败,因此您会发现自己陷入了开发者地狱。

As others have pointed out

  • both are equivalent apart from default visibility
  • there may be reasons to be forced to use the one or the other for whatever reason

There's a clear recommendation about when to use which from Stroustrup/Sutter:

Use class if the class has an invariant; use struct if the data members can vary independently

However, keep in mind that it is not wise to forward declare sth. as a class (class X;) and define it as struct (struct X { ... }).
It may work on some linkers (e.g., g++) and may fail on others (e.g., MSVC), so you will find yourself in developer hell.

笑红尘 2024-07-12 03:59:15

它们几乎是同一件事。 感谢 C++ 的魔力,结构可以像类一样保存函数、使用继承、使用“new”创建等等。

唯一的功能区别是类以私有访问权限开头,而结构以公共开头。 这是为了保持与 C 的向后兼容性。

在实践中,我总是使用结构作为数据持有者,使用类作为对象。

They are pretty much the same thing. Thanks to the magic of C++, a struct can hold functions, use inheritance, created using "new" and so on just like a class

The only functional difference is that a class begins with private access rights, while a struct begins with public. This is the maintain backwards compatibility with C.

In practice, I've always used structs as data holders and classes as objects.

南风起 2024-07-12 03:59:15

你什么时候会选择使用struct
何时在 C++ 中使用类?

当我定义函子和 POD 时,我使用了 struct。 否则我使用class

// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
    bool operator()(int first, int second)
    { return first < second; }
};

class mycompare : public std::binary_function<int, int, bool>
{
public:
    bool operator()(int first, int second)
    { return first < second; }
};

When would you choose to use struct
and when to use class in C++?

I use struct when I define functors and POD. Otherwise I use class.

// '()' is public by default!
struct mycompare : public std::binary_function<int, int, bool>
{
    bool operator()(int first, int second)
    { return first < second; }
};

class mycompare : public std::binary_function<int, int, bool>
{
public:
    bool operator()(int first, int second)
    { return first < second; }
};
神经暖 2024-07-12 03:59:15

从技术上讲,两者在 C++ 中是相同的 - 例如,结构可能具有重载运算符等。

但是:

当我希望同时传递多种类型的信息时,我使用结构
当我处理“功能”对象时,我使用类。

希望能帮助到你。

#include <string>
#include <map>
using namespace std;

struct student
{
    int age;
    string name;
    map<string, int> grades
};

class ClassRoom
{
    typedef map<string, student> student_map;
  public :
    student getStudentByName(string name) const 
    { student_map::const_iterator m_it = students.find(name); return m_it->second; }
  private :
    student_map students;
};

例如,我在此处的 get...() 方法中返回一个 struct Student - 享受吧。

Technically both are the same in C++ - for instance it's possible for a struct to have overloaded operators etc.

However :

I use structs when I wish to pass information of multiple types simultaneously
I use classes when the I'm dealing with a "functional" object.

Hope it helps.

#include <string>
#include <map>
using namespace std;

struct student
{
    int age;
    string name;
    map<string, int> grades
};

class ClassRoom
{
    typedef map<string, student> student_map;
  public :
    student getStudentByName(string name) const 
    { student_map::const_iterator m_it = students.find(name); return m_it->second; }
  private :
    student_map students;
};

For instance, I'm returning a struct student in the get...() methods over here - enjoy.

叹倦 2024-07-12 03:59:15

默认情况下,结构具有公共访问权限,而类默认具有私有访问权限。

我个人使用结构作为数据传输对象或值对象。 当这样使用时,我将所有成员声明为 const 以防止被其他代码修改。

Structs by default have public access and classes by default have private access.

Personally I use structs for Data Transfer Objects or as Value Objects. When used as such I declare all members as const to prevent modification by other code.

南风几经秋 2024-07-12 03:59:15

只是从 C++20 标准的角度解决这个问题(来自 N4860)。 ..

是一种类型。 关键字“class”和“struct”(以及“union”)在 C++ 语法中是 - class-key< /em>,选择 classstruct 的唯一功能意义是:

class-key 确定...默认访问是公共的还是私有的 (11.9)。

数据成员默认可访问性

11.9.1 中的示例记录了 class 关键字导致默认私有成员,而 `struct 关键字导致默认公共成员:

X类{
整数a; // X::a 默认是私有的:使用的类

...vs...

结构S {
整数a; // S::a 默认是公共的:使用结构

基类默认可访问性

1.9 还说:

如果基类没有访问说明符,则在使用类键定义派生类时假定为public > 当使用class-keyclass定义类时,假定structprivate

需要一致使用结构或类的情况......

有一个要求:

在类模板的重新声明、部分特化、显式特化或显式实例化中,类键应与原始类模板声明(9.2.8.3)一致。

...在任何详细类型说明符中,enum 关键字应用于引用枚举 (9.7.1)、union class-key 应用于引用union (11.5),以及classstruct< /code> class-key 应为
用于引用非联合类 (11.1)。


提供了以下示例(当不需要一致性时):

struct S { } s;
类 S* p = &s; // 好的

尽管如此,一些编译器可能会对此发出警告。


有趣的是,虽然您使用 structclassunion 创建的类型都称为“类”,但我们...

标准布局结构是使用class-key structclass-key<定义的标准布局类/em>


...所以在标准语言中,当谈到标准布局结构时,它使用“struct”来暗示“不是联合”。

我很好奇其他术语中是否有类似的“结构”用法,但对标准进行详尽的搜索是一项艰巨的工作。 欢迎评论。

Just to address this from a C++20 Standardese perspective (working from N4860)...

A class is a type. The keywords "class" and "struct" (and "union") are - in the C++ grammar - class-keys, and the only functional significance of the choice of class or struct is:

The class-key determines whether ... access is public or private by default (11.9).

Data member default accessibility

That the class keyword results in private-by-default members, and `struct keyword results in public-by-default members, is documented by the examples in 11.9.1:

class X {
int a; // X::a is private by default: class used

...vs...

struct S {
int a; // S::a is public by default: struct used

Base class default accessibility

1.9 also says:

In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.

Circumstances where consistent use of struct or class is required...

There's a requirement:

In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration (9.2.8.3).

...in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (9.7.1), the union class-key shall be used to refer to a union (11.5), and either the class or struct class-key shall be
used to refer to a non-union class (11.1).

The following example (of when consistency is not required) is provided:

struct S { } s;
class S* p = &s; // OK

Still, some compilers may warn about this.


Interestingly, while the types you create with struct, class and union are all termed "classes", we have...

A standard-layout struct is a standard layout class defined with the class-key struct or the class-key class.

...so in Standardese, when there's talk of a standard-layout struct it's using "struct" to imply "not a union"s.

I'm curious if there are similar use of "struct" in other terminology, but it's too big a job to do an exhaustive search of the Standard. Comments about that welcome.

ペ泪落弦音 2024-07-12 03:59:15

它们是相同的东西,但默认值不同(class 默认为 private,struct 默认为 public),因此理论上它们是完全可以互换的。

所以,如果我只是想打包一些信息来移动,我会使用一个结构,即使我在那里放置了一些方法(但不是很多)。 如果它是一个大部分不透明的东西,主要用途是通过方法,而不是直接用于数据成员,那么我使用完整的类。

they're the same thing with different defaults (private by default for class, and public by default for struct), so in theory they're totally interchangeable.

so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.

笑脸一如从前 2024-07-12 03:59:15

经过多年使用我的主要语言 C++ 进行编程后,我得出了一个明确的结论:这是 C++ 的另一个愚蠢功能。

两者之间没有真正的区别,我没有理由花额外的时间来决定是否应该将我的实体定义为结构体还是类。

要回答这个问题,请随时将您的实体定义为结构体。 默认情况下,成员将是公开的,这是常态。 但更重要的是,默认情况下继承将是公共的。 受保护的继承,甚至更糟糕的是私有继承,都是例外。

我从来没有遇到过私人继承是正确做法的案例。 是的,我尝试发明问题来使用私有继承,但没有成功。 而 Java,如果不使用访问器关键字,面向对象编程的角色模型默认为公共继承。 顺便说一句,Java 不允许在继承的类上使用访问器关键字,它们只能公开继承。 所以你可以看到,cpp团队在这里真的倒下了。

另一个令人沮丧的事情是,如果您定义为类并声明为结构,则会收到编译警告。 好像这会影响程序的性能或准确性。 一个答案还指出,MSVC 可能会传播编译器错误。

那些下雨时上课、晴天时上课的人,是根据他们所学的内容来这样做的。 他们发现这不是真的。 Java没有一对类名,只有class关键字。 如果您想要一个数据结构,只需将所有成员公开并且不要添加函数即可。 这在 Java 中有效,我没有看到任何问题。 有什么问题? 您需要 4 或 5 个字符的 BOM 代码来确定如何解释类​​实体的上下文。

After years of programming in C++, my main language, I come to the dead conclusion that this is another one of C++ dumb feature.

There is no real difference between the two, and no reason why I should spend extra time deciding whether I should define my entity as a struct or a class.

To answer this question, feel free to always define your entity as a struct. Members will be public by default which is the norm. But even more importantly, inheritance will be public by default. Protected inheritance, and even worse, private inheritance, are the exceptions.

I have never had a case where private inheritance was the right thing to do. Yes I tried to invent problems to use private inheritance but it didn't work. And Java, the role model of Object Oriented programming defaults to public inheritance if you don't use the accessor keywords. And by the way, Java doesn't allow accessor keywords on inherited classes, they can only be publicly inherited. So you can see, the cpp team really fell down here.

Another frustrating thing about this, is that if you define as a class and declare as a struct you get compilation warning. As though this is something that impacted the performance or accuracy of your program. One answer also noted that MSVC may propogate a compiler error instead.

Those persons that use classes when it is raining and structs when it is shining are doing so based on what they have been taught. It's not something they discovered to be true. Java does not have a pair of names for classes, and only have the class keyword. If you want a data structure, simply make all your members public and don't add functions. This works in Java and I don't see any problem. What's the problem? You need 4 or 5 characters of BOM code to determine how to interpret the context of a class entity.

最偏执的依靠 2024-07-12 03:59:15

班级。

类成员默认是私有的。

class test_one {
    int main_one();
};

相当于

class test_one {
  private:
    int main_one();
};

所以如果你尝试

int two = one.main_one();

我们会得到一个错误:main_one is private因为它不可访问。 我们可以
通过指定其公共即

class test_one {
  public:
    int main_one();
};

结构来初始化它来解决它。

结构体是一个类,其成员默认是公共的。

struct test_one {
    int main_one;
};

意味着 main_one 是私有的,即

class test_one {
  public:
    int main_one;
};

我使用结构作为数据结构,其中成员可以采用任何值,它是
这样更容易。

Class.

Class members are private by default.

class test_one {
    int main_one();
};

Is equivalent to

class test_one {
  private:
    int main_one();
};

So if you try

int two = one.main_one();

We will get an error: main_one is private because its not accessible. We can
solve it by initializing it by specifying its a public ie

class test_one {
  public:
    int main_one();
};

Struct.

A struct is a class where members are public by default.

struct test_one {
    int main_one;
};

Means main_one is private ie

class test_one {
  public:
    int main_one;
};

I use structs for data structures where the members can take any value, it's
easier that way.

哀由 2024-07-12 03:59:15

当我需要创建 POD 类型或函子时,我使用结构体。

I use structs when I need to create POD type or functor.

梦归所梦 2024-07-12 03:59:15

默认情况下,所有类成员都是私有的,所有结构成员默认都是公共的。
类具有默认的私有基,结构具有默认的公共基。 C 的结构不能有成员函数,而 C++ 的结构可以将成员函数添加到结构中。 除了这些差异之外,我没有发现它们有什么令人惊讶的地方。

All class members are private by default and all struct members are public by default.
Class has default private bases and Struct has default public bases. Struct in case of C cannot have member functions where as in case of C++ we can have member functions being added to the struct. Other than these differences, I don't find anything surprising about them.

想念有你 2024-07-12 03:59:15

仅当我需要保存一些没有任何关联成员函数的数据(对成员数据进行操作)并直接访问数据变量时,我才使用 struct。

例如:从文件和套接字流等中读取/写入数据。在函数参数太多且函数语法看起来太长的结构中传递函数参数。

从技术上讲,除了默认的可访问性之外,类和结构之间没有太大区别。
更重要的是,它取决于您如何使用它的编程风格。

I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.

Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.

Technically there is no big difference between class and struture except default accessibility.
More over it depends on programming style how you use it.

甜扑 2024-07-12 03:59:15

我认为结构旨在作为一种数据结构(如多数据类型信息数组),而类则用于代码打包(如子例程和函数的集合)..

:(

I thought that Structs was intended as a Data Structure (like a multi-data type array of information) and classes was inteded for Code Packaging (like collections of subroutines & functions)..

:(

ゞ花落谁相伴 2024-07-12 03:59:15

我从不在 C++ 中使用“struct”。

我无法想象当你想要私有成员时你会使用结构的场景,除非你故意试图混淆。

似乎使用结构更多的是如何使用数据的语法指示,但我宁愿创建一个类并尝试在类名称中或通过注释来明确这一点。

例如

class PublicInputData {
    //data members
 };

I never use "struct" in C++.

I can't ever imagine a scenario where you would use a struct when you want private members, unless you're willfully trying to be confusing.

It seems that using structs is more of a syntactic indication of how the data will be used, but I'd rather just make a class and try to make that explicit in the name of the class, or through comments.

E.g.

class PublicInputData {
    //data members
 };
等风来 2024-07-12 03:59:14

正如其他人指出的那样,实际上只有两种实际的语言差异:

  • struct 默认为公共访问,class 默认为私有访问。
  • 继承时,struct默认为public继承,class默认为private继承。 (讽刺的是,与 C++ 中的许多东西一样,默认值是向后的:public 继承是迄今为止更常见的选择,但人们很少声明 struct 只是为了节省时间输入“public”关键字,

但实践中真正的区别在于声明构造函数/析构函数的class/struct 和不声明构造函数/析构函数的class/struct。 “普通旧数据”POD 类型有一些保证,一旦您接管了类的构造,这些保证就不再适用。为了保持这种区别,许多人故意只使用 struct 。对于 POD 类型,如果他们要添加任何方法,请使用 classes。否则下面两个片段之间的差异毫无意义:(

class X
{
  public:

  // ...
};

struct X
{
  // ...
};

顺便说一句,这里有一个带有一些很好解释的线程。关于“POD 类型”的实际含义:C++ 中的 POD 类型是什么?

As everyone else notes there are really only two actual language differences:

  • struct defaults to public access and class defaults to private access.
  • When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

class X
{
  public:

  // ...
};

struct X
{
  // ...
};

(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

醉南桥 2024-07-12 03:59:14

C++ 中的 classstruct 之间的区别是:

  • struct 成员和基类/结构是 public默认。
  • 默认情况下,class 成员和基类/结构是private

类和结构都可以混合使用 publicprotectedprivate 成员,可以使用继承,并且可以具有成员函数。

我建议您:

  • 使用 struct 来表示没有任何类似类功能的普通旧数据结构;
  • 当您使用 privateprotected 成员、非默认构造函数和运算符等功能时,请使用 class

The differences between a class and a struct in C++ are:

  • struct members and base classes/structs are public by default.
  • class members and base classes/structs are private by default.

Both classes and structs can have a mixture of public, protected and private members, can use inheritance, and can have member functions.

I would recommend you:

  • use struct for plain-old-data structures without any class-like features;
  • use class when you make use of features such as private or protected members, non-default constructors and operators, etc.
百善笑为先 2024-07-12 03:59:14

现有的答案存在很多误解。

classstruct 都声明一个类。< /a>

是的,您可能需要重新排列类定义中的访问修改关键字,具体取决于您用来声明该类的关键字。

但是,除了语法之外,选择其中之一的唯一原因是约定/风格/偏好。

有些人喜欢对没有成员函数的类坚持使用 struct 关键字,因为生成的定义“看起来”像 C 中的简单结构。

同样,有些人喜欢使用 class code> 关键字用于具有成员函数和 private 数据的类,因为它上面写着“class”,因此看起来像他们最喜欢的面向对象编程书中的示例。

现实情况是,这完全取决于您和您的团队,并且它实际上对您的程序没有任何影响。

以下两个类除了名称之外在各方面都绝对等效:

struct Foo
{
   int x;
};

class Bar
{
public:
   int x;
};

您甚至可以在重新声明时切换关键字:(

class Foo;
struct Bar;

尽管这会破坏 Visual Studio 构建< /a> 由于不符合规定,因此当您执行此操作时,编译器将发出警告。)

并且以下表达式的计算结果均为 true:

std::is_class<Foo>::value
std::is_class<Bar>::value

但请注意,在重新定义<时,您无法切换关键字/em>; 这只是因为(根据单一定义规则)跨翻译单元的重复类定义必须“由相同的标记序列组成”。 这意味着您甚至无法将 const int member;int const member; 交换,并且与 class 或的语义无关结构

There are lots of misconceptions in the existing answers.

Both class and struct declare a class.

Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.

But, beyond syntax, the only reason to choose one over the other is convention/style/preference.

Some people like to stick with the struct keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.

Similarly, some people like to use the class keyword for classes with member functions and private data, because it says "class" on it and therefore looks like examples from their favourite book on object-oriented programming.

The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.

The following two classes are absolutely equivalent in every way except their name:

struct Foo
{
   int x;
};

class Bar
{
public:
   int x;
};

You can even switch keywords when redeclaring:

class Foo;
struct Bar;

(although this breaks Visual Studio builds due to non-conformance, so that compiler will emit a warning when you do this.)

and the following expressions both evaluate to true:

std::is_class<Foo>::value
std::is_class<Bar>::value

Do note, though, that you can't switch the keywords when redefining; this is only because (per the one-definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange const int member; with int const member;, and has nothing to do with the semantics of class or struct.

情独悲 2024-07-12 03:59:14

结构(POD,更一般地说)当您提供带有 C++ 实现的 C 兼容接口时,它们非常方便,因为它们可以跨语言边界和链接器格式移植。

如果这不是你关心的问题,那么我认为使用“结构”而不是“类”是一个很好的意图沟通者(正如 @ZeroSignal 上面所说)。 结构还具有更可预测的复制语义,因此它们对于您打算写入外部介质或通过网络发送的数据非常有用。

结构对于各种元编程任务也很方便,比如只公开一堆依赖的 typedef 的特征模板:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...但这实际上只是利用了结构的默认保护级别是公共的...

Structs (PODs, more generally) are handy when you're providing a C-compatible interface with a C++ implementation, since they're portable across language borders and linker formats.

If that's not a concern to you, then I suppose the use of the "struct" instead of "class" is a good communicator of intent (as @ZeroSignal said above). Structs also have more predictable copying semantics, so they're useful for data you intend to write to external media or send across the wire.

Structs are also handy for various metaprogramming tasks, like traits templates that just expose a bunch of dependent typedefs:

template <typename T> struct type_traits {
  typedef T type;
  typedef T::iterator_type iterator_type;
  ...
};

...But that's really just taking advantage of struct's default protection level being public...

欲拥i 2024-07-12 03:59:14

回答我自己的问题(无耻地),正如已经提到的,访问权限是它们在 C++ 中的唯一区别。

我倾向于仅使用结构来存储数据。 如果它能让数据处理变得更容易,我将允许它获得一些辅助函数。 然而,一旦数据需要流控制(即维护或保护内部状态的 getter/setter)或开始获取任何主要功能(基本上更像对象),它将“升级”为一个类,以更好地传达意图。

To answer my own question (shamelessly), As already mentioned, access privileges are the only difference between them in C++.

I tend to use a struct for data-storage only. I'll allow it to get a few helper functions if it makes working with the data easier. However as soon as the data requires flow control (i.e. getters/setters that maintain or protect an internal state) or starts acquring any major functionality (basically more object-like), it will get 'upgraded' to a class to better communicate intent.

痴情换悲伤 2024-07-12 03:59:14

对于 C++ 来说,结构和类之间确实没有太大区别。 主要的功能区别在于,结构体的成员默认是公共的,而在类中默认是私有的。 否则,就语言而言,它们是等效的。

也就是说,我倾向于在 C++ 中使用结构,就像在 C# 中一样,类似于 Brian 所说的。 结构是简单的数据容器,而类用于除了保存数据之外还需要对数据进行操作的对象。

For C++, there really isn't much of a difference between structs and classes. The main functional difference is that members of a struct are public by default, while they are private by default in classes. Otherwise, as far as the language is concerned, they are equivalent.

That said, I tend to use structs in C++ like I do in C#, similar to what Brian has said. Structs are simple data containers, while classes are used for objects that need to act on the data in addition to just holding on to it.

朱染 2024-07-12 03:59:14

结构对我有帮助的一个地方是当我有一个从另一个系统接收固定格式消息(例如串行端口)的系统时。 您可以将字节流转换为定义字段的结构,然后轻松访问这些字段。

typedef struct
{
    int messageId;
    int messageCounter;
    int messageData;
} tMessageType;

void processMessage(unsigned char *rawMessage)
{
    tMessageType *messageFields = (tMessageType *)rawMessage;
    printf("MessageId is %d\n", messageFields->messageId);
}

显然,这与在 C 中执行的操作相同,但我发现将消息解码为类的开销通常是不值得的。

One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.

typedef struct
{
    int messageId;
    int messageCounter;
    int messageData;
} tMessageType;

void processMessage(unsigned char *rawMessage)
{
    tMessageType *messageFields = (tMessageType *)rawMessage;
    printf("MessageId is %d\n", messageFields->messageId);
}

Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.

汐鸠 2024-07-12 03:59:14

正如大家所说,唯一真正的区别是默认访问权限。 但当我不想用简单的数据类进行任何类型的封装时,我特别使用 struct,即使我实现了一些辅助方法。 例如,当我需要这样的东西时:

struct myvec {
    int x;
    int y;
    int z;

    int length() {return x+y+z;}
};

As every one says, the only real difference is the default access. But I particularly use struct when I don't want any sort of encapsulation with a simple data class, even if I implement some helper methods. For instance, when I need something like this:

struct myvec {
    int x;
    int y;
    int z;

    int length() {return x+y+z;}
};
浊酒尽余欢 2024-07-12 03:59:14

如果您正在编写内部结构为 C++ 的库,但 API 可以由 C 或 C++ 代码调用,则可以在 C++ 中使用“struct”。 您只需创建一个包含向 C 和 C++ 代码公开的结构和全局 API 函数的标头,如下所示:

// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif

// Put your C struct's here
struct foo
{
    ...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;

// Put your C API functions here
void bar(foo *fun);

#ifdef __cpp
}
#endif

然后您可以使用 C++ 代码在 C++ 文件中编写函数 bar() 并使其可从 C 和两个世界可以通过声明的结构共享数据。 当然,混合 C 和 C++ 时还有其他注意事项,但这是一个简化的示例。

You can use "struct" in C++ if you are writing a library whose internals are C++ but the API can be called by either C or C++ code. You simply make a single header that contains structs and global API functions that you expose to both C and C++ code as this:

// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif

// Put your C struct's here
struct foo
{
    ...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;

// Put your C API functions here
void bar(foo *fun);

#ifdef __cpp
}
#endif

Then you can write a function bar() in a C++ file using C++ code and make it callable from C and the two worlds can share data through the declared struct's. There are other caveats of course when mixing C and C++ but this is a simplified example.

负佳期 2024-07-12 03:59:14

来自 C++ FAQ Lite

结构体的成员和基类默认是公共的,而在类中,它们默认是私有的。 注意:您应该将基类显式设置为公共、私有或受保护,而不是依赖默认值。

结构和类在其他方面在功能上是等效的。

好吧,关于干净利落的技术谈话已经够多了。 从情感上来说,大多数开发人员对类和结构进行了严格的区分。 结构就像一堆开放的位,几乎没有封装或功能。 类感觉就像社会中一个活跃且负责任的成员,具有智能服务、强大的封装屏障和定义良好的接口。 由于这是大多数人已经拥有的内涵,因此如果您有一个只有很少方法并且具有公共数据的类(这样的东西确实存在于设计良好的系统中!),您可能应该使用 struct 关键字,但否则您可能应该使用该类关键字。

From the C++ FAQ Lite:

The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

天涯离梦残月幽梦 2024-07-12 03:59:14

我唯一一次使用结构体而不是类是在函数调用中使用函子之前声明函子,并且为了清楚起见而希望最小化语法时。 例如:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare()); 

The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:

struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare()); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文