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

前端 未结 5 701
别跟我提以往
别跟我提以往 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 values;
    
    ...
    
    std::foreach(values.begin(); values.end(); doSomething);
    

提交回复
热议问题