仅用于数据的类与结构?

2021-12-09 00:00:00 class struct c++

在这种情况下,使用类比使用结构有什么优势吗?(注意:它只会保存变量,永远不会有函数)

Is there any advantage over using a class over a struct in cases such as these? (note: it will only hold variables, there will never be functions)

class Foo { 
private:   
   struct Pos { int x, y, z };
public:    
   Pos Position; 
};

对比:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

<小时>

类似问题:


Similar questions:

  • 什么时候应该使用类与C++ 中的结构体?
  • struct 和 class 有什么区别C++?
  • 我什么时候应该使用结构而不是班级?

推荐答案

使用一个并没有真正的优势,在 C++ 中,结构和类之间的唯一区别是其成员的默认可见性(结构默认为public,类默认为private).

There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private).

就我个人而言,我倾向于将结构用于 POD 类型,而将类用于其他所有类型.

Personally, I tend to prefer structs for POD types and use classes for everything else.

litb 在评论中提出了一个很好的观点,所以我要在这里引用他:

litb made a good point in the comment so I'm going to quote him here:

另一个重要的区别是结构派生自其他默认情况下,类/结构公共,而类通过私有派生默认.

one important other difference is that structs derive from other classes/struct public by default, while classes derive privately by default.

相关文章