【发布时间】:2021-07-06 14:44:48
【问题描述】:
这是我的代码:
class Base
{
virtual shared_ptr<Base> clone() const = 0;
};
class A : public Base
{
public:
A(const string &str) {
_str = str;
}
shared_ptr<Base> clone() const
{
return make_shared<A>(*this);
}
private:
string _str;
};
class B : public Base
{
public:
B() { }
B &AddToStorage(const string &key, Base &&val)
{
//_storage[key] = val; ?
//_storage[key] = val.clone(); ?
return *this;
}
shared_ptr<Base> clone() const
{
return make_shared<B>(*this);
}
private:
map<string, shared_ptr<Base>> _storage;
};
注意类 B 和它的方法 AddToStorage。如何使用 A 类和 B 类调用此函数?如:
B test;
test.AddToStorage("a", A("test1"));
test.AddToStorage("b", A("test2"));
test.AddToStorage("c", B());
当我访问 _storage (map) 时,我以后如何区分 A 类和 B 类?
编辑:我尝试实现克隆,但失败了 - https://www.fluentcpp.com/2017/09/08/make-polymorphic-copy-modern-cpp/ 遵循本教程,但似乎有一个错误“没有匹配函数调用 'A::A(const B&)'”
【问题讨论】:
标签: c++ class inheritance