我一直试图创建一个实例化派生类的类的复制构造函数,但没有成功。
假设我有以下纯虚拟类:
class AbstractBar{
public:
virtual void printMe() = 0;
};类Bar从AbstractBar继承如下:
class Bar: public AbstractBar {
std::string name_;
public:
explicit Bar(std::string name) : name_ {std::move(name)}{};
void printMe() override { std::cout << name_ << std::endl; }
};我的类Foo现在试图通过声明指向AbstractClass类型的指针来利用多态性,如下所示:
class Foo{
std::unique_ptr<AbstractBar> theBar_;
public:
explicit Foo(std::unique_ptr<Bar> bar){
theBar_ = std::move(bar);
};
void printBar(){
theBar_->printMe();
}
};但是,我确实希望复制Foo,因此我添加了以下复制构造函数:
Foo(const Foo &other) {
theBar_ = std::unique_ptr<AbstractBar>();
*theBar_ = *(other.theBar_);
}这就是它断裂的地方。
我认为这可能是一个问题,因为复制构造函数中的theBar认为它指向一个AbstractBar,但是当我试图复制它所指向的对象时,在下一行中,我实际上给它一个派生的Bar类。
是否有适当的方法来实现这个复制构造函数?
发布于 2022-02-17 12:15:33
首先,std::unique_ptr<T>确实是独一无二的。因此,您不能期望有两件事指向同一个实例--通过复制--任何实例。尽管如此,我认为您要做的是克隆unique_ptr成员持有的“东西”,以允许Foo的深度复制。
如果是这样的话,您需要一个协变克隆。见下文:
#include <iostream>
#include <string>
#include <memory>
struct AbstractBar
{
virtual ~AbstractBar() = default;
virtual std::unique_ptr<AbstractBar> clone() = 0;
virtual void printMe() = 0;
};
class Bar : public AbstractBar
{
std::string name_;
public:
explicit Bar(std::string name) : name_{std::move(name)} {};
std::unique_ptr<AbstractBar> clone() override
{
return std::make_unique<Bar>(name_);
}
void printMe() override
{
std::cout << name_ << std::endl;
}
};
class Foo
{
std::unique_ptr<AbstractBar> theBar_;
public:
explicit Foo(std::unique_ptr<Bar> bar)
: theBar_(std::move(bar))
{
}
Foo(const Foo &other)
: theBar_(other.theBar_->clone())
{
}
void printBar()
{
theBar_->printMe();
}
};
int main()
{
Foo foo(std::make_unique<Bar>("Some String"));
Foo bar(foo);
foo.printBar();
bar.printBar();
}重要:foo和bar将通过一个指向Bar抽象基(即AbstractBar )的唯一指针,各自拥有自己的Bar实例。希望这就是目的所在。这不是唯一的方法,但它可能是最容易理解的。
https://stackoverflow.com/questions/71157686
复制相似问题