什么时候应该在 C++ 中使用类和结构? [英] When should you use a class vs a struct in C++?
本文介绍了什么时候应该在 C++ 中使用类和结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C++ 中,struct
与 class
在什么情况下使用更好?
In what scenarios is it better to use a struct
vs a class
in C++?
推荐答案
class
和 struct
在 C++ 中的区别是:
The differences between a class
and a struct
in C++ is:
struct
成员和基类/结构默认为public
.class
成员和基类/struts 默认是private
.
struct
members and base classes/structs arepublic
by default.class
members and base classes/struts areprivate
by default.
类和结构都可以混合使用 public
、protected
和 private
成员,可以使用继承并可以具有成员函数.
Both classes and structs can have a mixture of public
, protected
and private
members, can use inheritance and can have member functions.
我会推荐你:
- 将
struct
用于没有任何类特征的普通旧数据结构; - 在使用
private
或protected
成员、非默认构造函数和运算符等功能时使用class
.莉>
- use
struct
for plain-old-data structures without any class-like features; - use
class
when you make use of features such asprivate
orprotected
members, non-default constructors and operators, etc.
这篇关于什么时候应该在 C++ 中使用类和结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文