【问题标题】:Member function not found after static cast from base to derived从基类到派生类的静态转换后找不到成员函数
【发布时间】:2019-09-27 04:50:23
【问题描述】:

我正在尝试构建一个名为“step”的函数,它接受一个基类指针并做一些事情。目前,我正在使用一个虚拟基类来启用一个通用接口。

#include <iostream>

using namespace std;

class gym_action //dummy base
{
public:
    virtual ~gym_action(){}
};

template<typename T>
class action_helper : public gym_action
{
    public :
        action_helper(T a) : action_item(a){}
        T get_action() {return action_item;}

    private:
       T action_item;

};

void step(gym_action* act)
{
    act = dynamic_cast<action_helper<int>*>(act);
    cout<<act->get_action()<<endl;
}

int main()
{

    action_helper<int> a(2);
//I will have more action_helper instansiations, like action_helper<Eigen::VectorXf> etc
    cout<<a.get_action()<<endl;
    step(&a);

}

此代码失败,gym_class 没有成员函数 get_action。很明显,这是因为基类中没有虚函数get_action

但是,我该如何定义呢?我目前不能的原因是每个模板化的get_action 函数返回不同的类型T。一种可能的方法是我提前在基类中定义所有可能的重载,但这似乎是一个糟糕的设计。有什么想法吗?

【问题讨论】:

    标签: c++ inheritance polymorphism c++14


    【解决方案1】:

    即使在dynamic_cast 之后,变量act 仍然是gym_action* 类型。因此,您不能在其上调用派生类成员函数。

    使用新变量。

    auto temp = dynamic_cast<action_helper<int>*>(act);
    if ( temp != nullptr )
    {
       cout << temp->get_action() << endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2021-01-15
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多