在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.
其他回答
它们几乎是一样的。由于c++的魔力,结构体可以像类一样保存函数、使用继承、使用“new”创建等等
唯一的功能区别是类以私有访问权限开始,而结构以public开始。这是对C语言的向后兼容。
在实践中,我总是使用结构体作为数据持有者,类作为对象。
现有的答案中有很多误解。
class和struct都声明一个类。
是的,您可能必须在类定义中重新安排访问修改关键字,这取决于您用于声明类的关键字。
但是,除了语法之外,选择一种而不是另一种的唯一原因是惯例/风格/偏好。
有些人喜欢对没有成员函数的类坚持使用struct关键字,因为最终的定义“看起来像”C中的简单结构。
类似地,有些人喜欢对具有成员函数和私有数据的类使用class关键字,因为它表示“类”,因此看起来像他们最喜欢的面向对象编程书籍中的示例。
实际上,这完全取决于您和您的团队,这对您的程序没有任何影响。
下面这两个类除了名字以外在其他方面都是完全等价的:
struct Foo
{
int x;
};
class Bar
{
public:
int x;
};
你甚至可以在重新声明时切换关键字:
class Foo;
struct Bar;
(虽然这将破坏Visual Studio构建由于不一致,所以编译器将发出一个警告,当你这样做。)
下面的表达式都为true:
std::is_class<Foo>::value
std::is_class<Bar>::value
不过,请注意,在重新定义时不能切换关键字;这只是因为(根据单定义规则)跨翻译单元的重复类定义必须“由相同的标记序列组成”。这意味着你甚至不能交换const int成员;,并且与类或结构的语义无关。
类。
默认情况下,类成员是私有的。
class test_one {
int main_one();
};
等于
class test_one {
private:
int main_one();
};
所以如果你尝试
int two = one.main_one();
我们将得到一个错误:main_one是私有的,因为它不可访问。我们可以 通过指定它的公共ie来初始化它来解决它
class test_one {
public:
int main_one();
};
结构体。
struct是一个类,其成员默认为public。
struct test_one {
int main_one;
};
意味着main_one是私有的,即
class test_one {
public:
int main_one;
};
我用struct表示数据结构,其中成员可以取任何值 那样容易些。
当你用c++实现提供兼容C的接口时,struct(更一般地说是PODs)非常方便,因为它们可以跨语言边界和链接器格式移植。
如果您不关心这一点,那么我认为使用“struct”而不是“class”是一种很好的意图交流方式(如上面的@ZeroSignal所述)。struct还具有更可预测的复制语义,因此对于打算写入外部媒体或通过网络发送的数据非常有用。
struct对于各种元编程任务也很方便,比如trait模板只暴露了一堆依赖的typedef:
template <typename T> struct type_traits {
typedef T type;
typedef T::iterator_type iterator_type;
...
};
...但这实际上只是利用了struct的默认保护级别是公共的……
默认情况下,所有类成员都是私有的,所有结构成员都是公共的。 类有默认的私有基,Struct有默认的公共基。Struct在C中不能有成员函数,而在c++中可以有成员函数被添加到Struct中。除了这些差异之外,我没有发现任何令人惊讶的地方。