struct VS. class
C++: struct Vs. class
Firstly, in C++, Both class and struct declare a class. The struct is intended for backward compatibility with C(different with C, because it is a class).
Accessibility
struct:have defaultpublicmembers and bases. It means when inheriting,structdefaults topublicinheritance.class:have defaultprivatemembers and bases. It means when inheriting,classdefaults toprivateinheritance.
Both directives allows a mixture of public, protected and private data and member functions.
In fact, two formats below are absolutely equivalent in every way except their name:
struct Foo
{
int x;
};
class Bar
{
public:
int x;
};
When to use:
- If we want to use structs as plain-old-data(POD) structures without any class-like features, then we need to use
struct. Note, thePODmeans that is a class (whether defined with the keyword struct or the keyword class) withoutconstructors,destructorsandvirtual members functions. - Then other situations is suitable to use
class.
Using struct as lambda function
struct Compare {bool operator() {...}};
std::sort(collection.begin(), collection.end(), Compare());
However, the lambda function has been supported in C++11 by all the major compilers.
Constructor
Since both directives are class, both are able to have constructor and destructor.
But some people would like to stick with the struct keyword for classes without member functions, because the resulting definition “looks like” a simple structure from C.
References
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 gzrjzcx@qq.com
文章标题:struct VS. class
文章字数:236
本文作者:Alex Zou
发布时间:2019-02-23, 01:03:10
最后更新:2024-07-10, 03:02:36
原始链接:https://www.hellscript.cc/2019/02/23/subposts_c/struct-VS-class/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。