G_20032222 2022-06-10 18:11 采纳率: 80%
浏览 125
已结题

关于#C++程序填空#的问题,如何解决?

这个代码怎么完善成对的呀

#include <iostream>
using namespace std;
class IndexError{};
template 

class ARRAY
{
    size_t m_size;
    T *m_ptr;
public:
    ARRAY(size_t size) : m_size(size)
    {    
        m_ptr = new T[size];    
        memset(m_ptr, 0, size*sizeof(int));
    }
    ~ARRAY()
    {    
        delete[] m_ptr;    
    }
    T& at(int index);
};

template <typename T>
::at(int index)  
{
    if(index<0||
)  
    {
        
 IndexError();  
    }
    return m_ptr[index];
}

int main()
{
    ARRAY<int> a(50);
    int i;
    cin >> i;
    
  
    {
        for(int j=0;j<i;j++)
            a.at(i) = j;
    }
    catch(IndexError e)
    {
        return 0;
    }
    return 0;
}

  • 写回答

1条回答 默认 最新

  • cnkeysky 2022-06-10 18:53
    关注
    
    #include <iostream>
    #include <cstring>
    using namespace std;
    class IndexError : public exception
    {
    public:
        const char *what()
        {
            return "下标越界异常";
        }
    };
    template <typename T>
    class ARRAY
    {
        size_t m_size;
        T *m_ptr;
    
    public:
        ARRAY(size_t size) : m_size(size)
        {
            m_ptr = new T[size];
            memset(m_ptr, 0, size * sizeof(int));
        }
        ~ARRAY()
        {
            delete[] m_ptr;
        }
        T &at(int index);
    };
    
    template <typename T>
    T &ARRAY<T>::at(int index)
    {
        if (index < 0 || index >= m_size)
        {
    
            throw IndexError();
        }
        return m_ptr[index];
    }
    
    int main()
    {
        ARRAY<int> a(50);
        int i;
        cin >> i;
        try
        {
            for (int j = 0; j < i; j++)
                a.at(i) = j;
        }
        catch (IndexError &e)
        {
            cout << e.what() << endl;
            return 0;
        }
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 6月18日
  • 已采纳回答 6月10日
  • 创建了问题 6月10日

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大