C++中的递归构造函数

Mat*_*ric 0 c++ constructor default-constructor

我构建了一个包含没有默认构造函数的向量的类.特别:

template<typename T>
struct MyVector
{
public:
  int GetN(void)
  {
    return n;
  }
  MyVector(int n1)
  {
    n=n1;
    ListElt = new T[n1];
  }
  ~MyVector()
  {
    delete [] ListElt;
  }
  // some other irrelevant to the question code
private:
  int n;
  T *ListElt;
};
Run Code Online (Sandbox Code Playgroud)

现在我想构建一个派生自它的类,它包含一个整数和一个向量.有效的代码如下:

struct EquivInfo {
public:
  EquivInfo(int inpOrbit, MyVector<int> &inpMat)
  {
    iOrbit=inpOrbit;
    eVect=new MyVector<int>(inpMat.getN());
    // some code for copying the vector in place.
  }
  ~EquivInfo()
  {
    delete eVect;
  }
private:
  int iOrbit;
  MyVector<int> *eVect;
};
Run Code Online (Sandbox Code Playgroud)

有没有办法避免使用向量的指针?

问题是如果我删除指针然后调用MyVector()类型的构造函数.我不懂为什么.应该有一种方法可以让EquivInfo的构造函数为MyVector调用一个精确的构造函数

我可以添加一个构造函数MyVector(),即一个将向量设置为微不足道的默认构造函数.但确切地说,我想避免使用这种构造函数,以便所有向量都被很好地定义并且代码是干净的.指针的使用让我有一个合理的情况,但我想知道是否有一个干净的方法来避免它.

Kri*_*izz 5

使用成员初始化列表:

class EquivInfo {
 public:
  EquivInfo(int inpOrbit, MyVector<int> &inpMat) 
    : eVect(inpMat.getN())
    , iOrbit(inpOrbit) {
    // some code for copying the vector in place.
   }

   // ....

   MyVector<int> eVect;
}
Run Code Online (Sandbox Code Playgroud)