AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > C++

C++中union的应用剖析

51自学网 http://www.wanshiok.com

  二、类中union的初始化

  由于union的共享内存特点,我们可以使我们的类存储不同的型别而不浪费内存空间,在类中我们可以声明一个union存储不同型别的指针,示例如下:

#pragma warning(disable : 4786)
#include

using namespace std;

class TestUnion
{
enum StoreType{Long,Const_CharP};
union
{
const char* ch_;
long l_;
} data_;
StoreType stype_;
TestUnion(TestUnion&);
TestUnion& operator=(const TestUnion&);
public:
TestUnion(const char* ch);
TestUnion(long l);
operator const char*() const {return data_.ch_;}
operator long() const {return data_.l_;}
};

TestUnion::TestUnion(const char* ch):data_.ch_(ch),stype_(Const_CharP)
{
}

TestUnion::TestUnion(long l):data_.l_(l),stype_(Long)
{
}

int main (void)
{
TestUnion pszobj("yuankai");
TestUnion lobj(1234);
cout<(pszobj)< cout<
return 0;
}

 
 

上一篇:C/C++建立IPC连接之后续操作  下一篇:浅析c/c++中的指针