Why should I even consider using structs in C++? [duplicate]

隐身守侯 提交于 2019-12-25 08:58:21

问题


Is there ever an advantage of declaring a struct in C++? Why shouldn't I just make a class consisting only of data members(i.e. no methods)?

Thanks,


回答1:


When you have a POD type where everything is public is saves a line...

struct Color {
    int r;
    int g;
    int b;
};

vs

class Color {
public:
    int r;
    int g;
    int b;
};

And it's also common practice for objects which are just dumb containers of things. Dumb meaning no constructors, operators, methods.




回答2:


My favorite reason is inheritance. consider this code:

class MyClass : public Base1, public virtual Base2 {
public:
    void fun1() override;

private:
    int m1;
};

Now consider this very example with a struct:

struct MyClass : Base1, virtual Base2 {
    void fun1() override;

private:
    int m1;
};

Some say C++ is too verbose, but when checking their code, it look much more like the first example. I find struct much easier to read than class. In my project I use struct everywhere.

The question you should ask is "Why should I even consider using classes in C++?", because IMO, struct are the same but less verbose.



来源:https://stackoverflow.com/questions/39926134/why-should-i-even-consider-using-structs-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!