我的class
,struct
和union
使用如下:
class
爲有行爲的對象。
struct
用於無源數據。
union
對於需要以不同類型訪問不同數據的非常特殊情況。
我在Google C++ Style guide很久以前閱讀本(除union
點),我是繼自那以後。
使用struct
s來攜帶被動數據(沒有行爲附加到對象的對象)具有成員默認公開的優點,因此可以在沒有Getters和Setter的情況下訪問它們。如果某些成員數據在分配之前需要檢查/修改,或者某些成員數據需要在得到之前進行計算/修改,恕我直言,他們需要一個Setter/Getter對,而對象是class
而不是struct
。
對於union
類型,我發現它對於某種數據結構,需要一些怪異訪問成員,或需要一些成員能夠在某些情況下其他類型進行治療是有用的。例如,一個三維向量或IP地址:
union 3DVector
{
double x, y, z;
double vector[3];
} v;
// Acess members with name
v.x = 6.0; v.y = 7.0; v.z = 8.0;
// Acess members as a vector
Normalize(v.vector);
union IPAddress
{
int binary;
char octet[4];
} ip;
// Acess the binary address
std::cout << std::hex << ip.binary << '\n';
// Print in a human-readable form
std::cout << static_cast<int>(ip.octet[0]) << '.'
<< static_cast<int>(ip.octet[1]) << '.'
<< static_cast<int>(ip.octet[2]) << '.'
<< static_cast<int>(ip.octet[3]) << '\n';
上述功能可以實現運算符重載和轉換操作符,但union
方法看起來整齊我。
的union
S能也作爲模板,並可以有構造函數/析構函數,這可能是序列化的目的(所有類型的對象沒有)有用:
template <typename T> union Serializer
{
Serializer(const T &o) : object(o) {}
T object;
char binary[sizeof(T)];
};
SomePODObject obj; // Only POD objects please!
Serializer s(obj);
SendBuffer(s.binary);
http://stackoverflow.com/questions/7950689/when-to-use-a-union-and-when-to-use-a-structure – acraig5075
工會與其他兩個人有很大的不同。 – chris
如果你沒有一個很好的理由來使用'union',那就不要。 – aschepler