我有一些英雄类是从抽象类 Warrior 扩展而来的:
enum Warrior_ID { Infantryman_ID=0, Archer_ID, Horseman_ID };
class Warrior
{
public:
virtual void info() = 0;
virtual ~Warrior() { }
static unique_ptr<Warrior> createWarrior( Warrior_ID id );
};
class Infantryman: public Warrior
{
public:
void info()
{
cout << "Infantryman" << endl;
}
};
class Archer: public Warrior
{
public:
void info()
{
cout << "Archer" << endl;
}
};
class Horseman: public Warrior
{
public:
void info()
{
cout << "Horseman" << endl;
}
};
这是我的工厂方法,返回特定字符:
unique_ptr<Warrior> Warrior::createWarrior( Warrior_ID id )
{
unique_ptr<Warrior> p;
switch (id)
{
case Infantryman_ID:
p = new Infantryman(); //this doesn't work
break;
case Archer_ID:
p = new Archer(); //this doesn't work
break;
case Horseman_ID:
p = new Horseman(); //this doesn't work
break;
default:
}
return p;
};
如何在不使用 make_unique 的情况下返回具有特定字符的 unique_ptr?
最佳答案
std::unique_ptr
的 pointer constructor是明确的,所以你需要
p = std::unique_ptr<Warrior>{new Infantryman{}};
或者,使用 reset()
成员函数:
p.reset(new Infantryman{});
如评论中所述,您实际上不需要声明局部变量 p
然后修改它。您可以直接从开关 block 返回:
case Infantryman_ID:
return std::unique_ptr<Warrior>{new Infantryman{}};
case Archer_ID:
return std::unique_ptr<Warrior>{new Archer{}};
等等。
关于c++ - 如何从工厂方法返回 unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45785613/