首页 > 技术文章 > C++实现元组

jshan 2013-12-02 16:36 原文

     一般我们使用struct时需要在头文件中定义,例如

struct Example

{

  int a;

  char b;

  ...

};

这样将数据打包好必须在程序运行之前将其定义好,如果有需求在程序运行时添加数据,就无法达到目的。

例如我需要向Example通过读取文件的方法来定义它所包含的变量。在python中。有一个结构叫做元组,如{“abcd”,1,1.23}。它可以存放各种类型的数据,并且可以动态添加或者删除。我需要用C++实现元组的形式。

思路很简单,我们写一个类CAnyType,此类可以存放各种类型的数据并且只能存放一个数据。如CAnyType a,b,c...

a="hello world"

b='a'

c=1

...

class CAnyType //: public CObject
{
public:
    CAnyType();
    //DECLARE_SERIAL(CAnyType)
    virtual ~CAnyType();

protected:
    
    CString DataType;
    union{
        int myint;
        double mydouble;
        float myfloat;
        wchar_t mychar;
        CString mystring;
      };

public:
    CAnyType operator=(const int &in){myint=in;DataType=L"int";return *this;}
    CAnyType operator=(const wchar_t &in){mychar=in;DataType=L"char";return *this;}
    CAnyType operator=(const float &in){myfloat=in,DataType=L"float";return *this;}
    CAnyType operator=(const double &in){mydouble=in;DataType=L"double";return *this;}
    CAnyType operator=(const LPCTSTR lpctstring){mystring=lpctstring;DataType=L"string";return *this;}
}

我们首先将基础数据类型或可能用到的数据类型放入类中做成员变量,为了节省内存,可放入联合中。

然后我们为每种数据类型重载操作符=,这个类现在就可以接受预定的任意数据类型了。如果需要其他操作(大于,小于等),可自己重载操作符。

最后我们需要制成一个元组只需new一个数组就完成了。

CAnyType *a=new CAnyType[size]

为元组赋值

 a[0]=1.1

a[1]=2

...

a[size-1]="end"

 

推荐阅读