我有一个名为Base
的抽象类,我从中派生了一个类(Derived
),如下所示:
#include <iostream>
#include <string>
#include <memory>
class Base
{
public:
virtual void printClass()const = 0;
virtual ~Base(){}
};
class Derived: public Base
{
private:
int m_var1;
std::string m_var2;
public:
Derived() = default;
Derived(const int& v1, const std::string& v2)
:m_var1(v1), m_var2(v2)
{ }
void printClass()const override
{
std::cout << "Derived Class with\t";
std::cout << m_var1 << " " << m_var2 << std::endl;
}
~Derived(){ std::cout << "Derived destroyed" << std::endl; }
};
现在在main()
中使用多态性我可以声明如下:
int main()
{
std::shared_ptr<Base> Obj[3];
Obj[0] = std::make_shared<Derived>(1,"One");
Obj[1] = std::make_shared<Derived>(2,"Two");
Obj[2] = std::make_shared<Derived>(3,"Three");
for(const auto& it: Obj)
it->printClass();
return 0;
}
但是,我目前正在尝试详细了解std::shared_ptr<>()
及其自定义删除技术,我发现了以下声明。
std::shared_ptr<Base> Obj(new Derived[3], [](Derived* obj){ delete[] obj; });
和
std::shared_ptr<Base> Obj(new Derived[3] = {
{1,"One"},
{2,"Two"},
{3,"Three"}
},
[](Derived* obj){ delete[] obj; });
我的问题是:
Derived
类的构造函数,即使我有一个服装定义的构造函数可用于derived
类?还是我错过了什么? derived class
元素数组?答案 0 :(得分:1)
您可以像这样调用构造函数:
std::shared_ptr<Base> Obj{
new Derived[3]{ {1,"One"}, {2,"Two"}, {3,"Three"} },
[](Derived* obj){ delete[] obj; }
};