C++: When should I use structs instead of classes

2019-03-10 23:03发布

  • When should I use a struct instead of a class? I'm currently using classes for everything from OpenGL texture wrappers to bitmap fonts.

  • Is a class that I use just like a struct (no making usage of inheritance, polymorphism, etc.) still slower than a struct?

标签: c++ oop struct
5条回答
We Are One
2楼-- · 2019-03-10 23:07

as others have explained, they're the same thing except for default access levels.

the only reason why classes can be perceived to be slower is because a good style (but not the only one) is the one mentioned by ArmenTsirunyan: struct for POD types, class for full-fledged object classes. The latter ones usually include inheritance and virtual methods, hence vtables, which are slightly slower to call than straight functions.

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-10 23:14

I like to use classes when I need to have an explicit destructor. Because then, you should be following the rule of three, in which case you need to write a copy constructer and assignment overloader. With all of this, it seems more natural to use a class than a struct.

查看更多
姐就是有狂的资本
4楼-- · 2019-03-10 23:19

Structs and classes in C++ as you may know differ solely by their default access level (and default accessibility of their bases: public for struct, private for class).

Some developers, including myself prefer to use structs for POD-types, that is, with C-style structs, with no virtual functions, bases etc. Structs should not have behavior - they are just a comglomerate of data put into one object.

But that is naturally a matter of style, and obviously neither is slower

查看更多
贪生不怕死
5楼-- · 2019-03-10 23:24

1) There is no real difference between the 2 other than the fact that struct members are, by default, public where classes are private.

2) No its EXACTLY the same.

Edit: Bear in mind you can use virtual inheritance with structs. They are THAT identical :)

查看更多
Melony?
6楼-- · 2019-03-10 23:32

Instead of cheaping out and referring to other questions, I'll re-iterate what others have said before I add on to them.

struct and class are identical in C++, the only exception being that struct has a default access of public, and class has a default access of private. Performance and language feature support are identical.

Idiomatically, though, struct is mostly used for "dumb" classes (plain-old-data). class is used more to embody a true class.

In addition, I've also used struct for locally defined function objects, such as:

struct something
{
    something() : count(0) { }
    void operator()(int value) { std::cout << value << "-" << count++ << "\n"; }
    int count;
} doSomething;

std::vector<int> values;

...

std::foreach(values.begin(); values.end(); doSomething);
查看更多
登录 后发表回答