这编译好,但在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;
}
答案 0 :(得分:1)
在涉及多态性和覆盖基类函数时,您忘记了一个非常重要的事情:函数必须是virtual
。
由于您的函数不是 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(){};
};
答案 1 :(得分:0)
显然,virtual
声明中遗失了Base::hello()
,override
之后InheritedA::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;
}
。
string-array