在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
我从来不在c++中使用struct。
我无法想象在需要私有成员时使用结构体的场景,除非您故意试图混淆。
使用结构体似乎更像是一种如何使用数据的语法指示,但我宁愿只创建一个类,并尝试在类的名称中显式地表示它,或通过注释。
E.g.
class PublicInputData {
//data members
};
其他回答
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++的魔力,结构体可以像类一样保存函数、使用继承、使用“new”创建等等
唯一的功能区别是类以私有访问权限开始,而结构以public开始。这是对C语言的向后兼容。
在实践中,我总是使用结构体作为数据持有者,类作为对象。
对于c++来说,结构体和类之间并没有太大的区别。主要的功能区别是,结构的成员在默认情况下是公共的,而在类中默认情况下是私有的。否则,就语言而言,它们是等价的。
也就是说,我倾向于在c++中使用结构体,就像我在c#中做的那样,类似于Brian所说的。struct是简单的数据容器,而类用于对象,除了保存数据外,还需要对数据进行操作。
正如其他人指出的那样
除了默认可见性之外,两者都是等效的 无论出于什么原因,都可能有理由被迫使用其中一种或另一种
关于何时使用Stroustrup/Sutter给出了明确的建议:
如果类有不变量,则使用class;如果数据成员可以独立变化,则使用struct
然而,请记住,将某事物前向声明为类(class X;)并将其定义为struct (struct X{…})。 它可能在某些链接器上工作(例如g++),但可能在其他链接器上失败(例如MSVC),所以你会发现自己陷入了开发人员的地狱。
摘自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.
推荐文章
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- 如何在方法中访问“静态”类变量?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- String, StringBuffer和StringBuilder
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?