在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
它们是一样的,只是默认值不同(class默认为private, struct默认为public),所以理论上它们是完全可以互换的。
所以,如果我只是想打包一些信息来移动,我使用一个结构体,即使我在那里放了一些方法(但不是很多)。如果它是一个最不透明的东西,其中主要使用将通过方法,而不是直接到数据成员,我使用一个完整的类。
其他回答
摘自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对我有帮助的一个地方是,当我有一个系统从另一个系统接收固定格式的消息(通过串行端口)时。您可以将字节流转换为定义字段的结构,然后轻松访问这些字段。
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中所做的事情相同,但我发现必须将消息解码为类的开销通常是不值得的。
默认情况下,所有类成员都是私有的,所有结构成员都是公共的。 类有默认的私有基,Struct有默认的公共基。Struct在C中不能有成员函数,而在c++中可以有成员函数被添加到Struct中。除了这些差异之外,我没有发现任何令人惊讶的地方。
正如其他人所指出的那样,真正的语言差异只有两个:
Struct默认为公共访问,class默认为私有访问。 继承时,struct默认为公共继承,class默认为私有继承。(具有讽刺意味的是,与c++中的许多东西一样,默认是反向的:公共继承是迄今为止更常见的选择,但人们很少声明结构只是为了节省键入“public”关键字。
但在实践中,真正的区别在于声明构造函数/析构函数的类/结构与未声明构造函数/析构函数的类/结构之间的区别。对于“普通的旧数据”POD类型有一定的保证,一旦接管类的构造就不再适用。为了明确这种区别,许多人故意只对POD类型使用结构体,如果他们要添加任何方法,则使用类。下面两个片段之间的区别是没有意义的:
class X
{
public:
// ...
};
struct X
{
// ...
};
(顺便提一句,这里有一个线程,对“POD类型”的实际含义有一些很好的解释:c++中的POD类型是什么?)
如果你写的库内部是c++,但API可以被C或c++代码调用,你可以在c++中使用"struct"。你只需要创建一个包含struct和全局API函数的头文件,就可以向C和c++代码公开,如下所示:
// C access Header to a C++ library
#ifdef __cpp
extern "C" {
#endif
// Put your C struct's here
struct foo
{
...
};
// NOTE: the typedef is used because C does not automatically generate
// a typedef with the same name as a struct like C++.
typedef struct foo foo;
// Put your C API functions here
void bar(foo *fun);
#ifdef __cpp
}
#endif
然后,您可以使用c++代码在c++文件中编写函数栏(),并使其可从C调用,两个世界可以通过声明的结构共享数据。当然,在混合使用C和c++时还有其他注意事项,但这是一个简化的示例。
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- 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
- 保护可执行文件不受逆向工程的影响?