C++模板實現數組類


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM