C++: When should I use structs instead of classes and where are the speed differences?

前端 未结 5 699
别跟我提以往
别跟我提以往 2021-02-02 10:42
  • 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

相关标签:
5条回答
  • 2021-02-02 11:10

    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);
    
    0 讨论(0)
  • 2021-02-02 11:11

    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.

    0 讨论(0)
  • 2021-02-02 11:13

    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.

    0 讨论(0)
  • 2021-02-02 11: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

    0 讨论(0)
  • 2021-02-02 11:21

    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 :)

    0 讨论(0)
提交回复
热议问题