When should you use a class vs a struct in C++?

后端 未结 25 2116
误落风尘
误落风尘 2020-11-22 00:18

In what scenarios is it better to use a struct vs a class in C++?

25条回答
  •  日久生厌
    2020-11-22 00:54

    As every one says, the only real difference is the default access. But I particularly use struct when I don't want any sort of encapsulation with a simple data class, even if I implement some helper methods. For instance, when I need something like this:

    struct myvec {
        int x;
        int y;
        int z;
    
        int length() {return x+y+z;}
    };
    

提交回复
热议问题