首页 > 解决方案 > 派生类方法中的基类参数

问题描述

这是我的代码:

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++classinheritance

解决方案


如何使用 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,并且(理想情况下)在其中覆盖它AB执行不同的操作。使用完全没有虚函数的指针来管理类层次结构是相当可疑的,因此您可能至少应该拥有一个。


推荐阅读