在c++中,在哪些情况下使用结构体比使用类更好?


当前回答

struct相对于class的一个优点是,如果坚持“首先是public成员,然后是private成员”,它可以节省一行代码。从这个角度来看,我发现关键字class毫无用处。

下面是只使用struct而不使用class的另一个原因。c++的一些代码风格指南建议使用小写字母表示函数宏,其基本原理是当宏转换为内联函数时,不需要更改名称。我也一样。你有了漂亮的c风格结构体,有一天,你发现你需要添加一个构造函数,或者一些方便的方法。你会把它改成一个类吗?到处都是吗?

区分结构体和类实在是太麻烦了,妨碍了我们做应该做的事情——编程。像c++的许多问题一样,它产生于向后兼容的强烈愿望。

其他回答

我认为Structs是作为一个数据结构(像一个多数据类型的信息数组)和类是为代码打包(像子例程和函数的集合)而设计的。

:(

它们是一样的,只是默认值不同(class默认为private, struct默认为public),所以理论上它们是完全可以互换的。

所以,如果我只是想打包一些信息来移动,我使用一个结构体,即使我在那里放了一些方法(但不是很多)。如果它是一个最不透明的东西,其中主要使用将通过方法,而不是直接到数据成员,我使用一个完整的类。

正如每个人所说,唯一真正的区别是默认访问。但是,当我不想对简单的数据类进行任何形式的封装时,即使实现了一些helper方法,我也会特别使用struct。例如,当我需要这样的东西时:

struct myvec {
    int x;
    int y;
    int z;

    int length() {return x+y+z;}
};

摘自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.

当我需要创建POD类型或函子时,我使用结构体。