2016-12-26 122 views
0

在C++中可以做到这一点吗?继承:从基类调用派生类函数

class Base { 
    int a(Derived d) { d.b(); } 
}; 

class Derived : public Base { 
    int b(); 
}; 

我应该在Base.hpp中包含Derived.hpp吗?

+0

在'Base'中创建'b()'纯虚函数。 –

+0

欢迎使用堆栈溢出。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –

+0

使用前向声明和定义中的分割声明,您的示例可能有效。但我不确定你展示的是什么你真正想要的。 – Jarod42

回答

1

在C++中可以做到这一点吗?

是的,这是在C++语言的使用非常简单,基本的模式(称为多态性或Template Method Pattern):

class Base { 
    int a() { b(); } // Note there's no parameter needed! 
// Just provide a pure virtual function declaration in the base class 
protected:  
    virtual int b() = 0; 

}; 

class Derived : public Base { 
    int b(); 
}; 
+0

您必须记住不要在构造函数或析构函数中调用这些函数,否则您将以纯函数调用结束。 – paweldac

+0

@paweldac幸运的是,在OP的示例中并非如此。如果需要这样做,你的答案可以解决这个问题。 –

+0

只是想向其他可能使用提议代码的读者说清楚。没错,在OP的问题中,这个错误不会出现:) – paweldac

0

下编译:

class Derived; 

class Base { 
public: 
    int a(Derived d); 
}; 

class Derived : public Base { 
public: 
    int b() { return 42; } 
}; 

int Base::a(Derived d) { d.b(); } 
+0

它编译,是的。虽然我担心这不是问题(正如你在评论中提到的那样)。 –

0

这是可能的调用函数从C++习惯用语的基类派生类调用:“好奇地重现模板模式”CRTP。请在下面找到以下呼叫:

template <class Child> 
struct Base 
{ 
    void foo() 
    { 
     static_cast<Child*>(this)->bar(); 
    } 
}; 

struct Derived : public Base<Derived> 
{ 
    void bar() 
    { 
     std::cout << "Bar" << std::endl; 
    } 
}; 
+0

这是另一种方法,是的。 –