本文介绍了使用类模板初始化指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

我遇到以下代码的问题(启动指针数组)。





模板< class elementtype =>



类MyVector

{

public:

MyVector(int TotalEntries);

~MyVector();

bool Add(MyVector& a,MyVector * res);



私人:

elementType * Arr;

int totalElements;



};



bool MyVector< int> :: Add(MyVector& a,MyVector * res)

{

if(totalElements == a.GetTotalEntries())

{

//我如何初始化它?

res = new elementType [totalElements + 1];

}

}

Hey,
I am having some problem with the following code (Initilization of pointer array).


template <class elementtype="">

class MyVector
{
public:
MyVector(int TotalEntries);
~MyVector();
bool Add(MyVector &a,MyVector *res);

private:
elementType *Arr;
int totalElements;

};

bool MyVector<int>::Add( MyVector &a,MyVector *res)
{
if( totalElements == a.GetTotalEntries() )
{
//How can I initialize it??
res = new elementType [ totalElements + 1 ];
}
}

推荐答案

template < typename T >
class CPodVector
{
...
protected:

T* m_pData;
unsigned int m_Length;
unsigned int m_Capacity;
};





为了利用这个,我会做类似的事情:



To make use of this I would do something like:

CPodVector< double > APodVector;
double dTest = 3.14159265;
unsigned long ulIndex = 0;
bool bResult = APodVector.insert( 0, dTest );





两个 CPodVector APodVector 实例上调用的函数将是 contructor 插入函数,它是......上面的一部分,就像是一样。





The two CPodVector functions that get called on the APodVector instance would be the contructor and the insert function which are part of the ... above and go something like.

//constructor
inline CPodVector() : m_pData(0), m_Length(0), m_Capacity(0)
{
}











and

//insert
bool insert( unsigned long ulIndex, const T& item )
{
  if( m_Length == m_Capacity && !grow())
  {
    return false;
  }

  T* dst = m_pData + ulIndex;
  memmove( dst + 1, dst, m_Length - ulIndex );
  memcpy( dst, &item, sizeof(T) );
  m_Length++;
  return true;
}





当然这是来自专业容器的片段,一般来说你应该使用std :: vector经过全面测试和可靠,具有良好的性能和文档。



Of course this is a snippet from a specialist container, in general you should be using std::vector which is thoroughly tested and reliable and has good performance and documentation.


这篇关于使用类模板初始化指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 02:30