【发布时间】:2020-10-08 22:51:19
【问题描述】:
正如答案所指出的,这是我犯的一个愚蠢的错误,与多态性或智能指针无关。更正的版本在接受的答案中。
============== 原问题 ==================
我正在尝试使智能指针与多态一起工作。在下面的原型代码中,纯virtual函数Base::print()的实现应该在Derived对象的内存块中。 DerivedWrap 可以访问指向 Derived 对象的指针。
为什么DerivedWrap::print()不能访问函数实现?
using namespace std;
class Base
{
public:
virtual void print() = 0;
};
class Derived : public Base
{
public:
Derived(int in) : i(in) {}
void print() {
cout << "int is " << i << endl;
}
private:
int i;
};
class DerivedWrap
{
public:
DerivedWrap() : DerivedWrap(make_unique<Derived>(2)) {}
DerivedWrap(unique_ptr<Base> pBase) : _pBase(move(pBase)) {}
void print()
{
_pBase->print();
}
private:
unique_ptr<Base> _pBase;
};
int main()
{
DerivedWrap pDW1();
pDW1->print(); // error: request for member ‘print’ in ‘pDW1’, which is of non-class type ‘DerivedWrap()’
DerivedWrap pDW2(make_unique<Derived>(2));
pDW2->print(); // error: base operand of ‘->’ has non-pointer type ‘DerivedWrap’
return 0;
}
【问题讨论】:
标签: c++ class c++11 polymorphism smart-pointers