C++中struct和class有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/92859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the differences between struct and class in C++?
提问by palm3D
This question was already asked in the context of C#/.Net.
这个问题已经在 C#/.Net 的上下文中提出了。
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
现在我想了解 C++ 中结构和类之间的区别。请讨论技术差异以及在 OO 设计中选择其中一种的原因。
I'll start with an obvious difference:
我将从一个明显的区别开始:
- If you don't specify
public:
orprivate:
, members of a struct are public by default; members of a class are private by default.
- 如果不指定
public:
orprivate:
,结构的成员默认是公共的;类的成员默认是私有的。
I'm sure there are other differences to be found in the obscure corners of the C++ specification.
我确信在 C++ 规范的晦涩角落中还可以找到其他差异。
回答by Assaf Lavie
You forget the tricky 2nd difference between classes and structs.
你忘记了类和结构之间棘手的第二个区别。
Quoth the standard (§11.2.2 in C++98 through C++11):
引用标准(C++98 到 C++11 中的第 11.2.2 节):
In absence of an access-specifierfor a base class, public is assumed when the derived class is declared structand private is assumed when the class is declared class.
在不存在的访问说明符为基类,当派生的类声明,假定公共 结构和私人当假设所述类被声明类。
And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):
为了完整起见,类和结构之间更广为人知的区别在(11.2)中定义:
Member of a class defined with the keyword classare privateby default. Members of a class defined with the keywords structor unionare publicby default.
默认情况下,使用关键字 class 定义的类的成员是私有的。默认情况下,使用关键字struct或union定义的类的成员 是公共的。
Additional difference: the keyword class
can be used to declare template parameters, while the struct
keyword cannot be so used.
附加区别:关键字class
可用于声明模板参数,而struct
关键字不能如此使用。
回答by Rob?
Quoting The C++ FAQ,
引用C++ FAQ,
[7.8] What's the difference between the keywords struct and class?
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.
[7.8] 关键字struct和class有什么区别?
结构体的成员和基类默认是公共的,而在类中,它们默认是私有的。注意:您应该使您的基类明确公开、私有或受保护,而不是依赖于默认值。
否则,结构和类在功能上是等效的。
好的,足够干净的技术谈话。在情感上,大多数开发人员在类和结构之间做出了很大的区分。结构体感觉就像一堆开放的位,几乎没有封装或功能。一个类就像一个有生命的、负责任的社会成员,拥有智能服务、强大的封装屏障和定义明确的接口。由于这是大多数人已经拥有的含义,如果您有一个方法很少且具有公共数据的类(这种东西确实存在于设计良好的系统中!),您可能应该使用 struct 关键字,否则您可能应该使用该类关键词。
回答by Jon Hanna
It's worth remembering C++'s origins in, and compatibility with, C.
值得记住 C++ 的起源以及与 C 的兼容性。
C has structs, it has no concept of encapsulation, so everything is public.
C 有结构体,它没有封装的概念,所以一切都是公开的。
Being public by default is generally considered a bad idea when taking an object-oriented approach, so in making a form of C that is natively conducive to OOP (you can do OO in C, but it won't help you) which was the idea in C++ (originally "C With Classes"), it makes sense to make members private by default.
在采用面向对象的方法时,默认情况下公开通常被认为是一个坏主意,因此在制作一种本机有利于 OOP 的 C 形式(您可以在 C 中执行 OO,但它不会帮助您)这是在 C++ 中的想法(最初是“C With Classes”),默认情况下将成员设为私有是有意义的。
On the other hand, if Stroustrup had changed the semantics of struct
so that its members were private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).
另一方面,如果 Stroustrup 更改了 的语义struct
,使其成员默认为私有,则会破坏兼容性(它不再像标准分歧那样普遍,但所有有效的 C 程序也是有效的 C++ 程序,这对 C++ 的立足点产生了很大的影响)。
So a new keyword, class
was introduced to be exactly like a struct, but private by default.
因此,class
引入了一个新关键字,与结构完全一样,但默认情况下是私有的。
If C++ had come from scratch, with no history, then it would probably have only one such keyword. It also probably wouldn't have made the impact it made.
如果 C++ 是从零开始的,没有历史,那么它可能只有一个这样的关键字。它也可能不会产生它所产生的影响。
In general, people will tend to use struct when they are doing something like how structs are used in C; public members, no constructor (as long as it isn't in a union, you canhave constructors in structs, just like with classes, but people tend not to), no virtual methods, etc. Since languages are as much to communicate with people reading the code as to instruct machines (or else we'd stick with assembly and raw VM opcodes) it's a good idea to stick with that.
一般来说,人们在做类似 C 中如何使用结构体的事情时会倾向于使用结构体;公共成员,没有构造函数(只要它不在联合中,你就可以在结构中拥有构造函数,就像类一样,但人们往往不这样做),没有虚方法等。因为语言与交流一样多人们阅读代码以指导机器(否则我们会坚持使用汇编和原始 VM 操作码),坚持这样做是个好主意。
回答by Kasprzol
Class' members are private by default. Struct's members are public by default. Besides that there are no other differences. Also see this question.
默认情况下,类的成员是私有的。Struct 的成员默认是公开的。除此之外没有其他区别。另请参阅此问题。
回答by crashmstr
According to Stroustrup in the C++ Programming Language:
根据 Stroustrup 在C++ 编程语言中的说法:
Which style you use depends on circumstances and taste. I usually prefer to use
struct
for classes that have all data public. I think of such classes as "not quite proper types, just data structures."
您使用哪种风格取决于环境和品味。我通常更喜欢
struct
用于所有数据都是公开的类。我认为这样的类“不是很合适的类型,只是数据结构”。
Functionally, there is no difference other than the public / private
功能上,除了public/private没有区别
回答by 64BitBob
STRUCT is a type of Abstract Data Type that divides up a given chunk of memory according to the structure specification. Structs are particularly useful in file serialization/deserialization as the structure can often be written to the file verbatim. (i.e. Obtain a pointer to the struct, use the SIZE macro to compute the number of bytes to copy, then move the data in or out of the struct.)
STRUCT 是一种抽象数据类型,它根据结构规范划分给定的内存块。结构在文件序列化/反序列化中特别有用,因为结构通常可以逐字写入文件。(即获取指向结构的指针,使用 SIZE 宏计算要复制的字节数,然后将数据移入或移出结构。)
Classes are a different type of abstract data type that attempt to ensure information hiding. Internally, there can be a variety of machinations, methods, temp variables, state variables. etc. that are all used to present a consistent API to any code which wishes to use the class.
类是一种不同类型的抽象数据类型,它试图确保信息隐藏。在内部,可以有各种阴谋、方法、临时变量、状态变量。等等,它们都用于向希望使用该类的任何代码提供一致的 API。
In effect, structs are about data, classes are about code.
实际上,结构是关于数据的,类是关于代码的。
However, you do need to understand that these are merely abstractions. It's perfectly possible to create structs that look a lot like classes and classes that look a lot like structs. In fact, the earliest C++ compilers were merely pre-compilers that translates C++ code to C. Thus these abstractions are a benefit to logical thinking, not necessarily an asset to the computer itself.
但是,您确实需要了解这些只是抽象。创建看起来很像类的结构和看起来很像结构的类是完全可能的。事实上,最早的 C++ 编译器只是将 C++ 代码转换为 C 的预编译器。因此,这些抽象有利于逻辑思维,而不一定是计算机本身的资产。
Beyond the fact that each is a different type of abstraction, Classes provide solutions to the C code naming puzzle. Since you can't have more than one function exposed with the same name, developers used to follow a pattern of _(). e.g. mathlibextreme_max(). By grouping APIs into classes, similar functions (here we call them "methods") can be grouped together and protected from the naming of methods in other classes. This allows the programmer to organize his code better and increase code reuse. In theory, at least.
除了每个都是不同类型的抽象这一事实之外,类还为 C 代码命名难题提供了解决方案。由于不能公开多个具有相同名称的函数,因此开发人员过去常常遵循 _() 模式。例如 mathlibextreme_max()。通过将 API 分组到类中,类似的函数(这里我们称它们为“方法”)可以组合在一起,并且不受其他类中方法命名的影响。这允许程序员更好地组织他的代码并增加代码重用。理论上,至少。
回答by Suraj K Thomas
1) Members of a class are private by default and members of struct are public by default.
1) 类的成员默认是私有的,结构体的成员默认是公有的。
For example program 1 fails in compilation and program 2 works fine.
例如程序 1 编译失败,程序 2 工作正常。
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
Run on IDE
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
2) 从类/结构派生结构时,基类/结构的默认访问说明符是公共的。派生类时,默认访问说明符是私有的。
For example program 3 fails in compilation and program 4 works fine.
例如程序 3 编译失败,程序 4 运行正常。
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}
Run on IDE
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equilalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}
回答by Skizz
The only other difference is the default inheritance of classes and structs, which, unsurprisingly, is private and public respectively.
唯一的其他区别是类和结构的默认继承,不出所料,它们分别是私有和公共的。
回答by Skizz
- The members of a structure are public by default, the members of class are private by default.
- Default inheritance for Structure from another structure or class is public.Default inheritance for class from another structure or class is private.
- 结构的成员默认是公共的,类的成员默认是私有的。
- 来自另一个结构或类的 Structure 的默认继承是公共的。来自另一个结构或类的类的默认继承是私有的。
class A{
public:
int i;
};
class A2:A{
};
struct A3:A{
};
struct abc{
int i;
};
struct abc2:abc{
};
class abc3:abc{
};
int _tmain(int argc, _TCHAR* argv[])
{
abc2 objabc;
objabc.i = 10;
A3 ob;
ob.i = 10;
//A2 obja; //privately inherited
//obja.i = 10;
//abc3 obss;
//obss.i = 10;
}
This is on VS2005.
这是在 VS2005 上。
回答by MSalters
Not in the specification, no. The main difference is in programmer expectations when they read your code in 2 years. structs are often assumed to be POD. Structs are also used in template metaprogramming when you're defining a type for purposes other than defining objects.
不在规范中,没有。主要区别在于程序员在 2 年内阅读您的代码时的期望。结构通常被假定为 POD。当您为定义对象以外的目的定义类型时,结构也用于模板元编程。