問題描述
什麼時候應該在 C++ 中使用類和結構? (When should you use a class vs a struct in C++?)
在什麼情況下在 C++ 中使用 struct
與 class
更好?
參考解法
方法 1:
The differences between a class
and a struct
in C++ is:
struct
members and base classes/structs arepublic
by default.class
members and base classes/struts areprivate
by default.
Both classes and structs can have a mixture of public
, protected
and private
members, can use inheritance and can have member functions.
I would recommend you:
- use
struct
for plain‑old‑data structures without any class‑like features; - use
class
when you make use of features such asprivate
orprotected
members, non‑default constructors and operators, etc.
方法 2:
As everyone else notes there are really only two actual language differences:
struct
defaults to public access andclass
defaults to private access.- When inheriting,
struct
defaults topublic
inheritance andclass
defaults toprivate
inheritance. (Ironically, as with so many things in C++, the default is backwards:public
inheritance is by far the more common choice, but people rarely declarestruct
s just to save on typing the "public
" keyword.
But the real difference in practice is between a class
/struct
that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain‑old‑data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use struct
s for POD types, and, if they are going to add any methods at all, use class
es. The difference between the two fragments below is otherwise meaningless:
class X
{
public:
// ...
};
struct X
{
// ...
};
(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)
方法 3:
There are lots of misconceptions in the existing answers.
Both class
and struct
declare a class.
Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.
But, beyond syntax, the only reason to choose one over the other is convention/style/preference.
Some people like to stick with the struct
keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.
Similarly, some people like to use the class
keyword for classes with member functions and private
data, because it says "class" on it and therefore looks like examples from their favourite book on object‑oriented programming.
The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.
The following two classes are absolutely equivalent in every way except their name:
struct Foo
{
int x;
};
class Bar
{
public:
int x;
};
You can even switch keywords when redeclaring:
class Foo;
struct Bar;
(although this breaks Visual Studio builds due to non‑conformance, so that compiler will emit a warning when you do this.)
and the following expressions both evaluate to true:
std::is_class<Foo>::value
std::is_class<Bar>::value
Do note, though, that you can't switch the keywords when redefining; this is only because (per the one‑definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange const int member;
with int const member;
, and has nothing to do with the semantics of class
or struct
.
方法 4:
The only time I use a struct instead of a class is when declaring a functor right before using it in a function call and want to minimize syntax for the sake of clarity. e.g.:
struct Compare { bool operator() { ... } };
std::sort(collection.begin(), collection.end(), Compare());
方法 5:
From the 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.
(by Alan Hinchcliffe、Commodore Jaeger、quark、Lightness Races in Orbit、Ferruccio、Tal Pressman)