在CArray中赋值的简单方法

时间:2014-05-22 00:52:28

标签: c++ arrays windows struct mfc

我必须在CArray中输入许多数据,哪个元素是结构,如下所示

CArray<structCtrlField, structCtrlField> aryDefTab1CtrlField;

structCtrlField sCtrlField1 = {CTRL_FIELD_ORDER_ERROR, _T(CTRL_FIELD_NAME_ERROR),
    _T(CTRL_FIELD_CODE_ERROR), 0};
theApp.aryDefTab1CtrlField.Add(sCtrlField1);
structCtrlField sCtrlField2 = {CTRL_FIELD_ORDER_ACTIVE, _T(CTRL_FIELD_NAME_ACTIVE),
    _T(CTRL_FIELD_CODE_ACTIVE), 0};
theApp.aryDefTab1CtrlField.Add(sCtrlField2);

我试着

theApp.aryDefTab1CtrlField[0] =  {CTRL_FIELD_ORDER_ERROR, _T(CTRL_FIELD_NAME_ERROR),
    _T(CTRL_FIELD_CODE_ERROR), 0};
theApp.aryDefTab1CtrlField[2] =  {CTRL_FIELD_ORDER_ACTIVE, _T(CTRL_FIELD_NAME_ACTIVE),
    _T(CTRL_FIELD_CODE_ACTIVE), 0};

但是编译器无法运行它......

如何定义aryDefTab1CtrlField?

1 个答案:

答案 0 :(得分:0)

你没有显示structCtrlField的声明,但我假设它是这样的(无论如何你都会得到这个想法):

struct structCtrlField
{
    CString szOne;
    CString szTwo;
    CString szThree;
    int nNum;
};

然后向结构添加成员函数以允许您设置字段:

struct structCtrlField
{
    CString szOne;
    CString szTwo;
    CString szThree;
    int nNum;

    void Set(LPCTSTR sz1, LPCTSTR sz2, LPCTSTR sz3, int n1)
    {
        // set members
        szOne = sz1;
        szTwo = sz2;
        szThree = sz3;
        nNum = n1;
    }
};

然后,使用您的示例代码,您可以像这样设置新值:

theApp.aryDefTab1CtrlField[0].Set(CTRL_FIELD_ORDER_ERROR, 
                                  _T(CTRL_FIELD_NAME_ERROR),
                                  _T(CTRL_FIELD_CODE_ERROR), 
                                  0);