Should I use structs in C++?

The difference between struct and class is small in C++, basically only that struct members are per default public and class members are per default private.

However, I still use structs whenever I need pure data structures, for instance:

struct Rectangle {
    int width;
    int height;
};

I find that very convenient to work with:

Rectangle r;
r.width = 20;
r.height = 10;

However, data structures are from procedural programming, and I'm doing object oriented programming. Is it a bad idea to introduce this concept into OO?


No. If it makes sense to use a struct somewhere, why would you complicate things using something else that isn't meant to fit the purpose ?

In my projects, I tend to use struct for simple "structures" which just need to hold some trivial data.

If a data structure needs to have some "smartness" and hidden fields/methods, then it becomes a class.


structs are especially useful for POD (plain old data) encapsulation. There is a lot more on this at struct vs class in C++


In my opinion, no, this is not a bad idea. If you're going to use a class in the same fashion, like

class Rectangle {
    public:
        int width;
        int height;
};

then you may as well use a struct . This will help make sure you're not forgetting to declare anything public, and if you keep it consistent, then future developers (including future you) will know that you intended this purely as a data object, not something to have methods within.

It's still pretty much an object from all usability perspectives, so no, it doesn't conflict with OO design.

链接地址: http://www.djcxy.com/p/40314.html

上一篇: 带有下划线前缀的类成员(

下一篇: 我应该使用C ++中的结构吗?