使用unique_ptr创建对象
Create object using unique_ptr
我enum class
了 3 种类型的对象。需要使用unique_ptr
创建适当类型的对象。但是编译器会抛出很多错误。其中之一:invalid new-expression of abstract class type 'ObjectManager'
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
也许我使用了错误的创建方法?
这是我的代码:
ObjectManager.h
class ObjectManager
{
public:
virtual void play(const std::string &sound) const = 0;
virtual void pause() const = 0;
virtual void stop() const = 0;
virtual void resume() const = 0;
};
对象类型.h
enum class ObjectType
{
type1,
type2,
type3
};
ObjectFactory.h
class ObjectFactory
{
private:
/* data */
public:
static unique_ptr<ObjectManager> create(ObjectType type);
};
对象工厂.cpp
static unique_ptr<ObjectManager> create(ObjectType type)
{
return make_unique<ObjectManager>(type);
}
主.cpp
auto createType = make_unique<ObjectManager>(ObjectType::type1);
我假设type1
、type2
和type3
映射到派生自ObjectManager
的类。我称它们为Manager1
,Manager2
和Manager3
如下:
std::unique_ptr<ObjectManager> ObjectFactory::create(ObjectType type)
{
switch(type) {
case ObjectType::type1: return std::make_unique<Manager1>();
case ObjectType::type2: return std::make_unique<Manager2>();
case ObjectType::type3: return std::make_unique<Manager3>();
}
return nullptr; // or {} or throw a runtime_error
}
还应向基类添加virtual
析构函数,否则基类指针上的delete
将不会调用派生类的析构函数。
class ObjectManager {
public:
//...
virtual ~ObjectManager() = default;
//...
};
由于您有一个工厂类,因此您应该在main
中使用它:
auto createType = ObjectFactory::create(ObjectType::type1);
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- ptr<Node> a = 创建对象 < 节点 > ();