码迷,mamicode.com
首页 > 编程语言 > 详细

C++模板实现数组类

时间:2018-08-11 17:15:32      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:public   define   c++   col   warnings   space   int   实现   temp   

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

 

C++模板实现数组类

标签:public   define   c++   col   warnings   space   int   实现   temp   

原文地址:https://www.cnblogs.com/seraphgabriel/p/9460262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!