【发布时间】:2015-09-17 18:14:38
【问题描述】:
我们有:
- 基类
Base; - 派生类
Derived。
声明:
class Derived : public Base
{
public:
Derived(); // ctor
~Derived(); // dtor
void MakeSomething();
private:
// some private stuff
}
现在我们进入我们的主要部分。这工作正常:
// ...
Derived derived;
derived.MakeSomething();
// ...
相反,这是行不通的:
// ...
boost::shared_ptr< Base > derived(new Derived);
derived->MakeSomething();
// ...
编译器说:
错误:类“Base”没有成员“MakeSomething”
我知道没有,其实我想调用Derived的方法!继承和指针缺少什么?
其他问题:
- 我不能在
Base中声明MakeSomething()virtual,因为Base属于我可以从中继承的第三方库; - 我还有其他类和方法需要我通过
boost::shared_ptr< Base >,我不能直接使用boost::shared_ptr< Derived >; - ...应该避免静态转换?
【问题讨论】:
-
Class
Base应该声明virtual void MakeSomething() = 0;(以及一个虚拟析构函数) -
...所以使用
boost::static_pointer_cast<Derived>(derived)->MakeSomething(); -
如果你想调用一个
Derived方法,获取一个指向Derived的指针。 -
...所以,从一开始就使用
boost::shared_ptr<Derived>,并在需要boost::shared_ptr<Base>时传递它? -
@LisaAnn
boost::shared_ptr<Derived>可隐式转换为boost::shared_ptr<Base>。你可以从一开始就使用前者
标签: c++ pointers inheritance shared-ptr