1

如何在 C++ 中为存储库分配内存?

这是存储库类:

class Repository{

private:
    DynamicVector<Medicine> MedList;
};

当我在 C 中使用结构时,initRepository 函数(构造函数)看起来像这样:

Repository* initRepository()
{
    Repository* repo =(Repository*)malloc(sizeof(Repository));
    repo->MedList=createVector();
    return repo;
}

但现在我想将 C 版本转换为 C++ 版本。我怎么做?

4

1 回答 1

2

你根本不需要做任何特别的事情。只需创建一个Repository对象:

Repository repo;

这将调用隐式定义的默认(如,默认行为)默认(如,不带参数)构造函数 for Repository,这也将构造成员MedList。一旦你有了你的Repository对象,你就可以对它做任何你喜欢的事情。

如果你想用函数MedList的结果初始化成员createVector,你可以定义你自己的默认构造函数,如下所示:

class Repository {
  public:
    Repository()
      : MedList(createVector())
    { }
  private:
    DynamicVector<Medicine> MedList;
};

这使用成员初始化列表(之后的所有内容:)来初始化MedList.

于 2013-03-30T16:12:38.547 回答