問題描述
在這種情況下,使用類比使用結構有什么優勢嗎?(注意:它只會保存變量,永遠不會有函數)
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.
這篇關于僅用于數據的類與結構?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!