《C++沉思录》-第十二章- 设计容器类

本文介绍了一个自定义的模板数组类CustomArray的设计与实现过程,该类提供了类似于标准C++数组的功能,支持下标访问、赋值等操作,并通过异常处理确保了程序的健壮性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计一个类似数组的类:

customarray.h

#ifndef CUSTOMARRAY_H
#define CUSTOMARRAY_H

template<class T>
class CustomArray
{
public:
    CustomArray(): m_data(0), m_size(0) {}

    CustomArray(unsigned size): m_size(size), m_data(new T[size]) {}

    ~CustomArray() { delete[] m_data; }

    const T& operator[](unsigned n) const
    {
        //防止溢出,健壮性
        //因为n是unsigned类型,所以不会 < 0
        if (n >= m_size || m_data == 0)
            throw "Array subscript out of range.";
        return m_data[n];
    }

    T& operator[](unsigned n)
    {
        if (n >= m_size || m_data == 0)
            throw "Array subscript out of range.";
        return m_data[n];
    }

    operator const T*() const
    {
        return m_data;
    }

    operator T*()
    {
        return m_data;
    }


private:
    T* m_data;
    unsigned m_size;
    //禁止 复制拷贝 以及 “=”赋值
    CustomArray(const CustomArray&);
    CustomArray& operator=(const CustomArray&);

};

#endif // CUSTOMARRAY_H

main.cpp


#include <iostream>
#include "customarray.h"
using namespace std;

int main(void)
{
    CustomArray<int> array(20);
    for (int i=0; i<20; i++)
    {
        array[i] = i;
    }
    for (int j=0; j<20; j++)
    {
        if (j%10 == 0)
            cout << endl;
        if (array[j] < 10)
            cout << "0";
        cout << array[j] << " ";
    }
    cout << endl;
    return 0;
}

运行结果:




00 01 02 03 04 05 06 07 08 09 
10 11 12 13 14 15 16 17 18 19 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值