C++模板实现数组类

#define  _CRT_SECURE_NO_WARNINGS
#include 


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::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;
}

 

转载于:https://www.cnblogs.com/seraphgabriel/p/9460262.html

你可能感兴趣的