C++结构体

C中的结构体和C++中结构体的不同之处:在C中的结构体只能自定义数据类型,结构体中不允许有函数,而C++中的结构体可以加入成员函数。

C++中的结构体和类的异同:
一、相同之处:结构体中可以包含函数;也可以定义public、private、protected数据成员;定义了结构体之后,可以用结构体名来创建对象。但C中的结构体不允许有函数;
              也就是说在C++当中,结构体中可以有成员变量,可以有成员函数,可以从别的类继承,也可以被别的类继承,可以有虚函数。

二、不同之处:结构体定义中默认情况下的成员是public,而类定义中的默认情况下的成员是private的。

实际上,C中的结构体只涉及到数据结构,而不涉及到算法,也就是说在C中数据结构和算法是分离的,而到C++中一类或者一个结构体可以包含函数(这个函数在C++我们通常中称为成员函数),C++中的结构体和类体现了数据结构和算法的结合。

例如:

struct CHGROUP
{
        unsigned short LOOPNum;
        unsigned short SPKMICNum;
        unsigned short MONITORNum;
        unsigned short TBNum;
        unsigned short AGENTNum;
        unsigned short HBNum;
        unsigned short VOIPNum;
private:
        CH *pLOOP;
        CH *pSPKMIC;
        CH *pMONITOR;
        CH *pTB;
        CH *pAGENT;
        CH *pVOIP;
        CH *pHB;
public:
        CHGROUP()
        {
                LOOPNum = SPKMICNum = MONITORNum = TBNum = AGENTNum = HBNum = VOIPNum = 0;
                pLOOP = pSPKMIC = pMONITOR = pTB = pAGENT = pHB = pVOIP = 0;
        }
     
        virtual ~CHGROUP()
        {
                if(LOOPNum) delete[]pLOOP;
                if(SPKMICNum) delete[]pSPKMIC;
                if(MONITORNum) delete[]pMONITOR;
                if(TBNum) delete[]pTB;
                if(AGENTNum) delete[]pAGENT;
                if(HBNum) delete[]pHB;
                if(VOIPNum) delete[]pVOIP;
        }

        void init(unsigned int type, unsigned int num)
        {
                if(num == 0)
                        return;
             
                CH *p = new CH[num];
             
                if(p==NULL)
                        return;

                switch(type)
                {
                case CHTYPE_LOOP:
                        pLOOP = p;
                        LOOPNum = num;
                        break;
                case CHTYPE_SPKMIC:
                        pSPKMIC = p;
                        SPKMICNum = num;
                        break;
                case CHTYPE_MONITOR:
                        pMONITOR = p;
                        MONITORNum = num;
                        break;
                case CHTYPE_TB:
                        pTB = p;
                        TBNum = num;
                        break;
                case CHTYPE_AGENT:
                        pAGENT = p;
                        AGENTNum = num;
                        break;
                case CHTYPE_HB:
                        pHB = p;
                        HBNum = num;
                        break;
                case CHTYPE_VOIP:
                        pVOIP = p;
                        VOIPNum = num;
                        break;
                default:
                        delete []p;
                        return;
                }
        }

     
上边是一个结构体,然后可以定义了struct CHGROUP chs;

调用函数来初始化
chs.init(CHTYPE_AGENT, num);

C++结构体

上一篇:Python:使用Scrapy框架的ImagesPipeline下载图片如何保持原图片名称呢?


下一篇:排序算法总结-python实现