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

Troubles with factory method with shared pointers and restricted constructors

这编译正常,但在 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;
}

在涉及多态性和重写基础-class 函数时,您忘记了一件非常重要的事情:函数必须是 virtual.

因为你的函数 不是 virtual 你调用了 Base::hello 函数,并且因为它没有 return 你想要的任何东西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,编译器将发出错误消息。

除了标记基础 class 函数 virtual,你真的应该 return 一些东西,任何东西,来自函数,或者使它摘要:

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(){};
};

显然 - virtualBase::hello() 声明中丢失,overrideInheritedA::hello() 之后。

#include <iostream>
#include <memory>

using namespace std;

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

protected:
    Base(){};
};


class InheritedA : public Base{
friend class Base;
public:
    string hello() override {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);
    //some very complex stuff here
    ptrB = dynamic_pointer_cast<Base>(ptrA);

    return ptrB;
};

int main() {

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


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