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