在C ++中什么时候应该使用类和结构体? [英] When should you use a class vs a struct in C++?
问题描述
在什么情况下,最好在C ++中使用 struct
vs ?
In what scenarios is it better to use a struct
vs a class
in C++?
推荐答案
类
与 struct
在C ++中结构有默认 public
成员和基础和类有默认私有
成员和基础。类和结构都可以混合使用 public
和 private
成员,可以使用继承并且可以有成员函数。类创建一个命名空间,它还封装了操作其数据元素的函数。类与C接口时不能使用,因为C没有类的概念。
Differences between a class
and a struct
in C++ are that structs have default public
members and bases and classes have default private
members and bases. Both classes and structs can have a mixture of public
and private
members, can use inheritance and can have member functions. Classes create a namespace that also encapsulates the functions for manipulating its data elements. Classes may not be used when interfacing with C, because C does not have a concept of classes.
我建议使用structs作为普通数据结构,没有任何类类似的特征,并且使用类作为具有私有
数据和成员函数的聚合数据结构。
I would recommend using structs as plain-old-data structures without any class-like features, and using classes as aggregate data structures with private
data and member functions.
这篇关于在C ++中什么时候应该使用类和结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!