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

关于#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 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据