使用类和结构体 [英] Use of class and struct
问题描述
可能的重复项:
在C ++中结构和类之间有什么区别
struct X{
};
class X{
};
同样的任务可以通过 class
以及 struct
。我的问题是我应该在哪里使用 class
和 struct
?
in C++, Same task can be done by class
as well as struct
. My question is where should I use class
and where struct
?
推荐答案
C ++中的struct和类之间的区别是:
The differences between a struct and class in C++ are:
- 类似地,默认情况下,类之间的继承也是私有的,默认情况下结构之间的继承是public。
<
但是基本上任何地方你使用一个结构体你可以使用一个类,反之亦然,所以它真的取决于你使用什么。通常,当你有方法时,使用一个类是更常见的,当你只有数据时,结构是更常用的。
But basically anywhere you use a struct you could use a class, and vice versa, so it's really up to you what to use. Conventionally, when you have methods, it is more common to use a class, and when you only have data, structs are more commonly used.
我会说,如果你想要所有的数据成员都是公共的,你没有方法,然后使用一个结构体。否则使用类。但这只是个人喜好。
I would say that if you want all the data members to be public, and you have no methods, then use a struct. Otherwise use a class. But that's just personal preference.
这篇关于使用类和结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!