使用类模板初始化指针? [英] Initializing Pointer with Class Template?

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

问题描述

嘿,

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





模板< 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 ];
}
}

推荐答案

我认为这里对C ++概念存在一些误解。您的添加成员函数不需要 a 参数。它已经是一个成员函数,这意味着它只能在 MyVector 的实例上调用。添加后不需要返回向量,因此不需要 res

我坐着看着现在非常相似的一个类

I think there''s some misunderstanding of C++ concepts here. Your Add member function doesn''t need the a parameter. It''s already a member function meaning it can only be called on an instance of MyVector. You don''t need to return the vector after you add to it either so res is not needed.
I''m sat looking at a class right now that is very similar
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.


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

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