在c++中,在哪些情况下使用结构体比使用类更好?
当前回答
回答我自己的问题(无耻地),正如已经提到的,访问权限是c++中它们之间的唯一区别。
我倾向于仅将结构体用于数据存储。我将允许它获得一些帮助函数,如果它使处理数据更容易的话。然而,一旦数据需要流控制(即维护或保护内部状态的getter /setter)或开始获得任何主要功能(基本上更像对象),它将被“升级”为一个类,以更好地传达意图。
其他回答
只是从c++ 20 standard的角度(从N4860工作)来解决这个问题…
类是一种类型。关键字“class”和“struct”(以及“union”)在c++语法中是“class-key”,选择class或struct的唯一功能意义是:
类键决定是否…默认情况下访问是public或private(11.9)。
数据成员默认可访问性
class关键字的结果是private-by-default成员,而' struct关键字的结果是public-by-default成员,在11.9.1的例子中有说明:
类X { int;// X::a默认为private:使用的类
对…
struct S { int;// S::a默认为public: struct被使用
基类默认可访问性
1.9还说:
在基类没有访问说明符的情况下,当派生类使用类键结构体定义时假定为public,当类使用类键类定义时假定为private。
需要一致使用结构体或类的情况……
有一个要求:
在类模板的重声明、部分特化、显式特化或显式实例化中,类键应与原始类模板声明一致(9.2.8.3)。
...在任何详细类型说明符中,枚举关键字应使用指向枚举(9.7.1),联合类键应使用指向联合(11.5),类或结构的类键必须是 用于指非并体类(11.1)。
以下是不需要一致性的例子:
struct S {} S; 类S* p = &s;/ /好吧
不过,一些编译器可能会对此提出警告。
有趣的是,虽然你用struct、class和union创建的类型都被称为“类”,但我们有…
标准布局结构体是用类键结构体或类键类定义的标准布局类。
...所以在标准语中,当谈到标准布局结构体时,它使用“struct”来暗示“不是联合”。
我很好奇在其他术语中是否也有类似的“struct”用法,但要对标准进行详尽的搜索,工作量太大了。欢迎对此发表评论。
如果你写的库内部是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++时还有其他注意事项,但这是一个简化的示例。
正如每个人所说,唯一真正的区别是默认访问。但是,当我不想对简单的数据类进行任何形式的封装时,即使实现了一些helper方法,我也会特别使用struct。例如,当我需要这样的东西时:
struct myvec {
int x;
int y;
int z;
int length() {return x+y+z;}
};
struct相对于class的一个优点是,如果坚持“首先是public成员,然后是private成员”,它可以节省一行代码。从这个角度来看,我发现关键字class毫无用处。
下面是只使用struct而不使用class的另一个原因。c++的一些代码风格指南建议使用小写字母表示函数宏,其基本原理是当宏转换为内联函数时,不需要更改名称。我也一样。你有了漂亮的c风格结构体,有一天,你发现你需要添加一个构造函数,或者一些方便的方法。你会把它改成一个类吗?到处都是吗?
区分结构体和类实在是太麻烦了,妨碍了我们做应该做的事情——编程。像c++的许多问题一样,它产生于向后兼容的强烈愿望。
摘自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.