结构体操作的坏味道

来源:互联网 发布:剪力弯矩图软件 编辑:程序博客网 时间:2024/06/02 18:32

今天在工程中调试BUG, 最后找到的原因是结构体拷贝时,忘拷贝了结构体成员变量.

那个结构是半年以前写的,定义在一个.h中.

结构体拷贝函数在另外的.h, .cpp中实现, 当时感觉味道很坏.

工程3W行, 在那个结构体中添加变量时,已经忘了找那个结构体的拷贝函数添加对应变量的拷贝操作.


今天找到BUG后,才发觉应该在结构体中,直接定义结构体的操作函数(拷贝,赋值,取值等操作).

感到欣慰的是,定义的结构体拷贝函数(Copy_TAG_XX)都在一处, 直接都改到结构体内实现.


/// @file       TestConsole.cpp/// @brief      验证deque's front() 方法#include "stdafx.h"#include <windows.h>#include <tchar.h>#include <string>namespace e_sex_type{    enum e_sex_type    {        unknown = 0,        man,        woman    };}typedef struct _tag_info{    int                     iAge;    std::wstring            strName;    e_sex_type::e_sex_type  eSexType;        _tag_info()    {        iAge = 0;        strName = L"";        eSexType = e_sex_type::e_sex_type::unknown;        /// ...        /// 后来被添加的变量定义    }        /// 在结构体内定义和结构体相关的函数,是比较好的    /// 当结构体增加变量时,不会忘了在拷贝函数中增加相应变量的拷贝    /// 如果对单独的结构体变量操作,在结构体内编制函数,也比在外面写函数好    void Copy(_tag_info* pSrc)    {        if (NULL == pSrc)            return;        this->iAge = pSrc->iAge;        this->strName = pSrc->strName.c_str();        this->eSexType = pSrc->eSexType;    }}TAG_INFO;void fnTest();int _tmain(int argc, _TCHAR* argv[]){    fnTest();    /** run result    InfoA.iAge = 20    */    _tprintf(L"\r\nEND, press anykey to quit\r\n");    getwchar();    return 0;}void fnTest(){    TAG_INFO InfoA;    TAG_INFO InfoB;    /// 从数据来源处,得到了数据    InfoB.iAge = 20;    InfoB.strName = L"testUsr1";    InfoB.eSexType = e_sex_type::e_sex_type::man;    /// 结构体的赋值    InfoA.Copy(&InfoB);    /// use InfoA do task ...    _tprintf(L"InfoA.iAge = %d\r\n", InfoA.iAge);}


0 0