使用基构造函数创建派生对象

creating derived object using base constructor

本文关键字:派生 对象 创建 构造函数      更新时间:2023-10-16

我正在将一行从CSV文件读取到向量中,然后我想将此向量传递到正确的派生类中,因此创建一个具有正确私有属性的对象。但是,如何将向量传递给基类,而不仅仅是派生对象?

基类:

class Material
{
public:
    Material() ;
    virtual ~Material() ;
    void addNewMaterial();
private:
    std::string type;
    std::string format;
    int idNumber;
    std::string filmTitle;
    std::string audioFormat;
    float runtime;
    std::string language;
    float retailPrice;
    std::string subtitles;
    std::string frameAspect;
    std::string bonusFeatures;
};

派生类:

class Disk : public Material
{
public:
   Disk(); 
   ~Disk();
private:
   std::string packaging;
   std::string audioFormat;
   std::string language;     //multiple language tracks
   std::string subtitles;   //subtitles in different languages
   std::string bonusFeatures; //bonus features
};

第二个派生类

    class ssDVD : public Disk
{
public:
    ssDVD(std::vector<std::string>);
    ~ssDVD();
private:
    //plastic box
};

我想创建一个新的 ssDVD,其中包含使用构造函数设置变量的基本 Material 类的属性。如何从派生对象访问和更改这些内容?

生类的构造函数需要将其参数传递给其超类的构造函数。

首先,在大多数情况下,将非 POD 函数参数作为常量引用传递更有效,以避免按值复制大型对象:

class ssDVD : public Disk {
public:
   ssDVD(const std::vector<std::string> &);
   // ...
};

然后,构造函数按值将其参数传递给超类的构造函数:

ssDVD::ssDVD(const std::vector<std::string> &v) : Disk(v)
   // Whatever else the constructor needs to do
{
   // Ditto...
}

当然,然后你必须让Disk 的构造函数做同样的事情,将参数传递给基类。

为了结束循环,如果您按值传递所有这些参数,则每个构造函数将创建矢量的单独副本。效率很低。通过使用常量引用,不会创建任何副本。