c++ - 派生类方法中的基类参数
问题描述
这是我的代码:
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&)'”
解决方案
如何使用 A 类和 B 类调用此函数?
两者std::shared_ptr<A>
和std::shared_ptr<B>
都可以转换为std::shared_ptr<Base>
,这是您的函数所期望的,因此提供共享指针将起作用。
test.AddToStorage("a", std::make_shared<A>("test1"));
test.AddToStorage("b", std::make_shared<A>("test2"));
test.AddToStorage("c", std::make_shared<B>());
当我访问 _storage (map) 时,我以后如何区分 A 类和 B 类?
为了区分它们,您需要在 中拥有一个虚函数Base
,并且(理想情况下)在其中覆盖它A
并B
执行不同的操作。使用完全没有虚函数的指针来管理类层次结构是相当可疑的,因此您可能至少应该拥有一个。
推荐阅读
- tensorflow - 即使Rasa_nlu和tensorflow安装成功如何解决ImportError
- c++11 - 基于范围的for循环引用
- ios - NotificationCenter - 视图之间的文本传输
- javascript - Webscrape JS 呈现网站
- git - 为新的主要更新创建单独的存储库?
- javascript - 如何使用带有 Codemirror 键绑定的 Ctrl+S 提交表单
- python - 提取 bs4 元素中的文本
- magento2 - 将 magento 1 转换为 magento 2
- javascript - Wordpress 媒体按钮设置
- android - 无法解析“?attr/actionBarSize”