C++模板实现数组类

家住魔仙堡 提交于 2020-03-26 09:20:17
#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>


using namespace std;

template<class T1>
class Person
{
public:
    Person(int len)
    {
        
        this->len = len;
        this->t = new T1[len];
        if (!this->t)
        {
            cout << "失败" << endl;
            exit(1);
        }
        for (int i = 0; i < len; i++)
        {
            (this->t)[i] = 0;
        }
    }
    Person(int len, T1* t)
    {

        this->len = len;
        this->t = new T1[len];
        if (!this->t)
        {
            cout << "失败" << endl;
            exit(1);
        }
        strcpy(this->t, t);
    }
    
    T1& operator[](int i);

    ~Person()
    {
        if (this->t != NULL)
        {
            delete[] t;
            t = NULL;
        }
    }

public:
    T1* t;
    int len;
};
template<class T1>
T1& Person<T1>::operator[](int i)
{
    if (i < 0 || i > this->len - 1)
    {
        cout << "越界了" << endl;
        exit(2);
    }
    return (this->t)[i];
}
void main()
{
    Person<int> a1(10);
    Person<char> a2(10, "123456789");
    
    cout << "----------" << endl;
    for (int i = 0; i < 10; i++)
    {
        a1[i] = i + 1;
    }
    for (int i(0); i < 10; i++)
    {
        cout << a1[i] << endl;
    }
    cout << "---------------" << endl;
    cout << a2.t << endl;
    return;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!