【问题标题】:c++ passing object which using abstract class type gives error: is not a member of GeneralDriverInterfacec++传递使用抽象类类型的对象给出错误:不是GeneralDriverInterface的成员
【发布时间】:2016-05-25 08:54:09
【问题描述】:

我有一个简单的通用界面,看起来像这样:

Class GeneralDriverInterface 
{
public:
virtual void Init() = 0;
};

然后我有一个使用初始化 GeneralDriverInterface 接口的子类之一的类。

 class DriverTest : public GeneralDriverInterface 
    {
        public: 
        DriverTest();
        virtual void Init();
        bool TestMe();

    }

    void DriverTest::Init()
    { 
       //init driver stuff 
    }

    bool DriverTest::TestMe()
    { 
       //test driver stuff 
    }

现在要使用这个 DriverTest 类,它会通过函数在类中初始化

// in the Processing.h header there is :

    GeneralDriverInterface* m_GeneralDriverInterface;
    void Processing::InitDriver(GeneralDriverInterface* _GeneralDriverInterface)
    {
       m_GeneralDriverInterface = _GeneralDriverInterface;
       m_GeneralDriverInterface->Init();
       m_GeneralDriverInterface->TestMe();  // The problematic call !! where it failed in compilation 
    }

它通过 GeneralFactory 类的构造函数获取它的 Driver 类,如下所示:

GeneralFactory::SetProcessingDriver()
{
    GeneralDriverInterface pGeneralDriverInterface = new DriverTest()
    m_pProcessing->InitDriver(pGeneralDriverInterface );
}

好的,我尝试使用抽象接口尽可能通用,但我得到了:

 error C2039: 'TestMe' : is not a member of 'GeneralDriverInterface'
1>        g:\project\GeneralDriverInterface.h(6) : see declaration of 'GeneralDriverInterface'

我的问题是我是否需要在实现的类中包含我要使用的所有功能?

【问题讨论】:

  • 您是否希望基类神奇地将其所有派生类的所有成员添加到自己的接口中?
  • 是的,你需要在界面中通过界面使用的所有功能。

标签: c++ interface pure-virtual


【解决方案1】:

m_GeneralDriverInterface 的类型为 GeneralDriverInterface

GeneralDriverInterface 没有方法TestMe()

我需要包含我将要使用的所有功能吗? 实现类的?

是的,是的。

编译器应该如何知道它应该调用什么样的方法?

【讨论】:

  • 贝茨先生,我想使用接口作为通用类型,但是每个实现接口的类也将有自己的功能
  • @user63898 你要么必须在你的基类中指定纯虚拟的其他方法(或者虚拟并且只在它们各自的类中实现它们),或者如果你确定你正在处理一个某种类型的对象你可以dynamic_cast指针然后调用相应的方法。
【解决方案2】:

我的问题是我是否需要在实现的类中包含我要使用的所有功能?

是的,您需要包含所有需要通过接口指针或引用使用的函数

在派生接口的类中实现的任何其他函数都不需要在那里声明。

您仍然可以使用dynamic_cast<>static_cast<> 来获取实现类的指针或引用。

【讨论】:

  • 嗯,这就是我希望在接口中拥有非常通用的方法,但实现该接口的子类将拥有自己的公共方法
  • @user63898 他们可以拥有自己的公共功能,除非您进行演员表,否则您无法通过界面访问这些功能。
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多