析构函数在模板类c:如何删除字段可能是指针或不是指针? [英] Destructor in template class c : How to delete field which may be pointer or not pointer?

查看:269
本文介绍了析构函数在模板类c:如何删除字段可能是指针或不是指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有模板类 Array ,其中模板类型 T 应该是指针或非指针类型。 / p>

I have template class Array where the template type T should be either pointer or not-pointer type.

template<class T>
class TArray
{   
     static const int max_len=100;
     T* data;
     int length;

  public:
     TArray(){data=new T[max_len]; this->length=0;} 
     void Add(T value){data[length++]=value;}   
     ~TArray();
};

问题是如何释放空间,因为我们不能调用 delete 对于不是这样的指针类型

The problem is how to free space, since we can not call delete for not pointer types like this

template<class T>
TArray<T>::~TArray()
{
    //for(int i =0; i < length; i++)
    //  delete data[i]; // NOT WORKING WITH OBJECTS THAT ARE NOT POINTERS !!!
    delete[] data;
}

让我们添加类

class A
{
    int* a;
  public:
    A(int n){a = new int[n];}
    ~A(){delete[] a;}
};

并创建模板类

// Create array of doubles
TArray<double>* double_array = new TArray<double>();
delete double_array;

// Create array of pointers to class A
TArray<A*>* A_array = new TArray<A*>();
A* a = new A(5);
A_array->Add(a);
delete A_array;

当我为 TArray< A *> 我需要为类 A 调用析构函数,但我不知道如何,因为destructor中的注释代码不是编译(C2541),如果我们做示例array

When I call destructor for TArray<A*> I need to call destructor for class A but I don't know how, since the commented code in destructor is not compile (C2541) if we make for example array of doubles.

推荐答案

您可以为您的模板开发两个版本。首先,写正常版本 template< class T> 。然后,通过声明这样

You can develop two versions for your template. First, write the normal version template<class T>. Then, write a second pointer-only version that specializes your template by declaring it like this:

template<class T>
class TArray<T*>

这篇关于析构函数在模板类c:如何删除字段可能是指针或不是指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆