c++ - 具有共享指针和受限构造函数的工厂方法的问题

标签 c++ polymorphism smart-pointers factory-pattern

这编译正常,但在 b->hello() 调用时给出运行时错误。我的意图是使用 b 指针的动态类型并调用 Inherited::hello() 版本。

帮助:-)

#include <iostream>
#include <memory>

using namespace std;

class Base {
public:
    static  shared_ptr<Base> factory();
    string hello(){};
    virtual ~Base() {};

protected:
    Base(){};
};


class InheritedA : public Base{
friend class Base;
public:
    string hello() {return "I am iA";}
protected:
    InheritedA() {};
};


shared_ptr<Base> Base::factory() {
    shared_ptr<Base>        ptrB;
    shared_ptr<InheritedA>  ptrA;
    ptrA = shared_ptr<InheritedA>(new InheritedA);

    ptrB = dynamic_pointer_cast<Base>(ptrA);

    return ptrB;
};

int main() {

    shared_ptr<Base> b;
    b = Base::factory();


    cout << b->hello();
    return 0;
}

最佳答案

当谈到多态性和覆盖基类函数时,您忘记了一件非常重要的事情:函数必须是虚拟的

因为你的函数不是 virtual 你调用了 Base::hello 函数,因为它不返回任何东西你会有undefined behavior ,导致您遇到崩溃。

您可以要求编译器通过使用 override specifier 来帮助您检测此类情况。 :

class InheritedA : public Base{
friend class Base;
public:
    string hello() override  // Tell the compiler that this function should
                             // override the function from the parent class
    {return "I am iA";}
protected:
    InheritedA() {};
};

如果您使用 override 说明符,如果函数不是 virtual,编译器将发出错误。

除了将基类函数标记为 virtual 之外,您真的应该从函数中返回一些东西,任何东西,或者将其抽象化:

class Base {
public:
    static  shared_ptr<Base> factory();

    // Make the function a pure abstract function that must be overridden
    virtual string hello() = 0;

    virtual ~Base() {};

protected:
    Base(){};
};

关于c++ - 具有共享指针和受限构造函数的工厂方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50153159/

相关文章:

java - 捕获返回基类型或派生类型的方法的返回值

c++ - 如果 unique_ptr 需要存储删除器,它怎么能没有开销?

rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T

c++ - TSTP(礼貌停顿)如何与我在 Linux 中的 C++ 程序交互?

c++ - 为什么不需要导出模板类?

C++ 检查未初始化的迭代器

class - 参数化类和多态性

java - 抽象类中的具体方法可以返回子类中定义的变量吗?

c++ - std::make_unique 可以将函数的输出作为参数吗?

c++ - 在 Qt 中为 QTableView 创建弹出菜单