TryCObArray.cpp

本文通过一个具体的CObArray使用案例,介绍了如何利用MFC的CObArray类进行对象数组的管理和操作,包括对象的创建、添加、访问及释放等过程。
// TryCObArray.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "TryCObArray.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

class CElement :public CObject
{
public:
    CElement(CString pType)
    {
        m_Type = pType ;
        TRACE("构造 *** %s\n", m_Type) ;
    }

    ~CElement()
    {
        TRACE("析构 --> %s\n", m_Type) ;
    }

    CString& GetContent()
    {
        return m_Type ;
    }

public:
    CString m_Type ;
} ;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // 初始化 MFC 并在失败时显示错误
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: 更改错误代码以符合您的需要
        _tprintf(_T("错误: MFC 初始化失败\n"));
        nRetCode = 1;
    }
    else
    {
        // TODO: 在此处为应用程序的行为编写代码。
        CObArray obaArray ;
        for ( int i = 0 ; i < 10 ; i++ )
        {
            CElement * pElement ;
            CString strTemp ;
            strTemp.Format(_T("%d"), i) ;
            pElement = new CElement(strTemp) ;
            obaArray.Add(pElement) ;
        }

        for (  i = 0 ; i < 10 ; i++ )
        {
            CElement * pElement ;
            //pElement = (CElement*)obaArray.GetAt(i) ;
			pElement = (CElement*)obaArray[i] ;
#ifdef UNICODE
            wcout << "访问到的元素是 " << (LPCTSTR)pElement->m_Type << endl ;
#else
            cout << "访问到的元素是 " << (LPCTSTR)pElement->m_Type << endl ;
#endif
        }

        // 使用操作符[]来访问元素
        for (  i = 0 ; i < 10 ; i++ )
        {
            CElement * pElement ;
            pElement = (CElement*)obaArray[i] ;
            delete pElement ;
        }
        obaArray.RemoveAll() ;
    }

    return nRetCode;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值