問(wèn)題描述
在這種情況下,使用類(lèi)比使用結(jié)構(gòu)有什么優(yōu)勢(shì)嗎?(注意:它只會(huì)保存變量,永遠(yuǎn)不會(huì)有函數(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;
};
對(duì)比:
struct Foo {
struct Pos { int x, y, z } Pos;
};
<小時(shí)>
類(lèi)似問(wèn)題:
Similar questions:
- 什么時(shí)候應(yīng)該使用類(lèi)與C++ 中的結(jié)構(gòu)體?
- struct 和 class 有什么區(qū)別C++?
- 我什么時(shí)候應(yīng)該使用結(jié)構(gòu)而不是班級(jí)?
推薦答案
使用一個(gè)并沒(méi)有真正的優(yōu)勢(shì),在 C++ 中,結(jié)構(gòu)和類(lèi)之間的唯一區(qū)別是其成員的默認(rèn)可見(jiàn)性(結(jié)構(gòu)默認(rèn)為public,類(lèi)默認(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).
就我個(gè)人而言,我傾向于將結(jié)構(gòu)用于 POD 類(lèi)型,而將類(lèi)用于其他所有類(lèi)型.
Personally, I tend to prefer structs for POD types and use classes for everything else.
litb 在評(píng)論中提出了一個(gè)很好的觀點(diǎn),所以我要在這里引用他:
litb made a good point in the comment so I'm going to quote him here:
另一個(gè)重要的區(qū)別是結(jié)構(gòu)派生自其他默認(rèn)情況下,類(lèi)/結(jié)構(gòu)公共,而類(lèi)通過(guò)私有派生默認(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ù)的類(lèi)與結(jié)構(gòu)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!