使用基构造函数创建派生对象
creating derived object using base constructor
我正在将一行从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
的构造函数做同样的事情,将参数传递给基类。
为了结束循环,如果您按值传递所有这些参数,则每个构造函数将创建矢量的单独副本。效率很低。通过使用常量引用,不会创建任何副本。
相关文章:
- 为什么此派生对象无法访问基类的后递减方法?
- 如何在新的派生对象中获取基本对象的数据?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 在没有默认构造函数的情况下创建的派生对象
- OOP 标识派生对象
- 如何创建派生对象的向量?
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何从 Gtk::窗口调用派生对象的析构函数
- 无法在派生对象上运行虚拟函数
- 尝试删除指向派生对象的基指针时断言错误
- 存储在一个通用容器中的派生对象.如何避免铸造
- 将派生对象分配给函数内的基类指针
- 替换派生对象向量中的对象"no matching function to call"
- 派生对象调用的 Base 方法的模板推导
- 用于填充 Base 和派生对象的 shared_ptr 向量的函数模板
- C++ UBSAN 对派生对象产生误报
- 如何验证我是否正在使用C++中的基对象或派生对象
- C++ 构造函数和派生对象
- 将派生对象传递给模板
- 指向派生作品的基本指针,即使派生对象不存在