問題描述
在這種情況下,使用類比使用結(jié)構(gòu)有什么優(yōu)勢嗎?(注意:它只會保存變量,永遠(yuǎn)不會有函數(shù))
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:
- 什么時候應(yīng)該使用類與C++ 中的結(jié)構(gòu)體?
- struct 和 class 有什么區(qū)別C++?
- 我什么時候應(yīng)該使用結(jié)構(gòu)而不是班級?
推薦答案
使用一個并沒有真正的優(yōu)勢,在 C++ 中,結(jié)構(gòu)和類之間的唯一區(qū)別是其成員的默認(rèn)可見性(結(jié)構(gòu)默認(rèn)為public,類默認(rèn)為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).
就我個人而言,我傾向于將結(jié)構(gòu)用于 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:
另一個重要的區(qū)別是結(jié)構(gòu)派生自其他默認(rèn)情況下,類/結(jié)構(gòu)公共,而類通過私有派生默認(rèn).
one important other difference is that structs derive from other classes/struct public by default, while classes derive privately by default.
這篇關(guān)于僅用于數(shù)據(jù)的類與結(jié)構(gòu)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!