什么时候应该在 C++ 中使用类和结构? [英] When should you use a class vs a struct in C++?

查看:35
本文介绍了什么时候应该在 C++ 中使用类和结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,structclass 在什么情况下使用更好?

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

推荐答案

classstruct 在 C++ 中的区别是:

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

  • struct 成员和基类/结构默认为 public.
  • class 成员和基类/struts 默认是 private.
  • struct members and base classes/structs are public by default.
  • class members and base classes/struts are private by default.

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

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

我会推荐你​​:

  • struct 用于没有任何类特征的普通旧数据结构;
  • 在使用privateprotected成员、非默认构造函数和运算符等功能时使用class.莉>
  • 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.

这篇关于什么时候应该在 C++ 中使用类和结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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