在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
struct对我有帮助的一个地方是,当我有一个系统从另一个系统接收固定格式的消息(通过串行端口)时。您可以将字节流转换为定义字段的结构,然后轻松访问这些字段。
typedef struct
{
int messageId;
int messageCounter;
int messageData;
} tMessageType;
void processMessage(unsigned char *rawMessage)
{
tMessageType *messageFields = (tMessageType *)rawMessage;
printf("MessageId is %d\n", messageFields->messageId);
}
显然,这与您在C中所做的事情相同,但我发现必须将消息解码为类的开销通常是不值得的。
其他回答
从技术上讲,这两者在c++中是相同的——例如,结构体可能具有重载操作符等。
然而:
当我希望同时传递多种类型的信息时,我使用结构体 当我处理一个“功能性”对象时,我使用类。
希望能有所帮助。
#include <string>
#include <map>
using namespace std;
struct student
{
int age;
string name;
map<string, int> grades
};
class ClassRoom
{
typedef map<string, student> student_map;
public :
student getStudentByName(string name) const
{ student_map::const_iterator m_it = students.find(name); return m_it->second; }
private :
student_map students;
};
例如,我在这里的get…()方法中返回一个struct student -喜欢。
对于c++来说,结构体和类之间并没有太大的区别。主要的功能区别是,结构的成员在默认情况下是公共的,而在类中默认情况下是私有的。否则,就语言而言,它们是等价的。
也就是说,我倾向于在c++中使用结构体,就像我在c#中做的那样,类似于Brian所说的。struct是简单的数据容器,而类用于对象,除了保存数据外,还需要对数据进行操作。
摘自c++ FAQ Lite:
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults. struct and class are otherwise functionally equivalent. OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.
struct和class在本质上是相同的,尽管在可见性方面有不同的默认值,struct的默认值是公共的,而类的默认值是私有的。您可以通过适当地使用private和public将其中一个更改为另一个。它们都允许继承、方法、构造函数、析构函数以及面向对象语言的所有其他优点。
然而,两者之间的一个巨大区别是C支持struct作为关键字,而class不支持。这意味着可以在包含文件中使用一个可以#include到c++或C中的结构体,只要该结构体是一个普通的C风格结构体,并且包含文件中的其他内容与C兼容,即没有c++特定的关键字,如private, public, no方法,no继承,等等等等。
C风格结构体可以与其他支持使用C风格结构体在接口上来回传输数据的接口一起使用。
C风格结构是一种模板(不是c++模板,而是一种模式或模板),用于描述内存区域的布局。多年来,C语言和C插件(这里是Java、Python和Visual Basic)已经创建了可用的接口,其中一些与C风格的结构体一起工作。
默认情况下,结构具有公共访问权限,类具有私有访问权限。
就我个人而言,我使用结构作为数据传输对象或作为值对象。当这样使用时,我将所有成员声明为const,以防止其他代码修改。