我想在多态情况下将派生类的unique_ptr所有权转移到其抽象基类unique_ptr中。该怎么做?
class Fruit {
public:
virtual void print() = 0;
};
class Apple: public Fruit {
public:
string name;
virtual void print() { cout << " Apple name is " << name << endl; }
Apple(string name): name(name) {}
};
int main()
{
unique_ptr<Apple> apple = make_unique<Apple>("Rose");
unique_ptr<Fruit> fruit = dynamic_cast<unique_ptr<Fruit>>(apple); // don't work
// want to transfer ownership of apple to fruit
unique_ptr<Apple> new_apple = dynamic_cast<unique_ptr<Apple>>(fruit); // get back the ownership to the new apple
return 0;
}
unique_ptr<Fruit> fruit = make_unique<Apple>("Rose");
应该可以工作。 - JohnFilleau