如何在 C++ 中使用向上转换 unique_ptr 指针仅引用派生 class 中定义的方法?

How to refer to a method defined in a derived class only, using an upcast unique_ptr pointer in C++?

假设以下 类

class Base
{
   void Doajob(a,b){...}
}

class Derived: public Base
{
   void Doanotherjob(a,b,c){...}
}

我定义了一个指针如下:

 auto ptr= unique_ptr<Base>(new Derived(name));

现在我想使用 ptr 指针访问 Doanotherjob:

ptr->Doanotherjob(a,b,c); // ERROR
((unique_ptr<Base>) ptr)->Doanotherjob(a,b,c); // ERROR
((unique_ptr<Derived>) ptr)->Doanotherjob(a,b,c); // ERROR

这是正确的做法吗?语法是什么?

如果你确定downcast是安全的,你可以使用static_cast

static_cast<derived*>(ptr.get())->DoAnotherJob(...);

但是,如果您在 base 中将 DoAnotherJob() 设为虚拟,则不需要向下转换。这是一种更为传统的面向对象方法。

如以下评论所述,dynamic_cast 让我们执行此转换并验证结果:

if(auto d = dynamic_cast<derived*>(ptr.get())
   d->DoAnotherJob();