从基类函数调用派生类函数

时间:2012-04-05 12:27:52

标签: c++ inheritance virtual

在下面的代码中,在类set(int, int)的函数Base中,我想调用派生类函数showK()。有没有办法做到这一点?

我无法在类showK()中声明Base函数,我无法将其设为虚拟。这对我来说是一个限制。

class Base{
    int i, j;
    public:
    void set( int, int );
    void show() { cout << i << " " << j << "\n"; }
};

void Base:: set(int a, int b)
{ 
    i=a; j=b; 
    //Here I want to call the function showk() of class derived . Is there a way to call?.
}

class derived : public base {
    int k;
    public:
    derived(int x) { k=x; }
    virtual void showk() { cout << k << "\n"; }
};

int main()
{
    derived ob(3);
    ob.set(1, 2); // access member of base
    ob.show(); // access member of base
    ob.showk(); // uses member of derived class
    return 0;
}

提前致谢。

3 个答案:

答案 0 :(得分:1)

当对象实际上不是该类型时调用派生方法可能导致未定义的行为。我认为你真正想要的是如果对象是派生类型的话,让set()方法调用showk()。它通常会这样做:

class Base{
    int i, j;
    public:
    virtual void set( int, int );
    void show() { cout << i << " " << j << "\n"; }
};

void Base:: set(int a, int b)
{ 
    i=a; j=b; 
}

class derived : public base {
    int k;
    public:
    derived(int x) { k=x; }
    virtual void set(int a,int b);
    virtual void showk() { cout << k << "\n"; }
};

void derived::set(int a,int b)
{
  base::set(a,b);
  showk();
}

int main()
{
    derived ob(3);
    ob.set(1, 2); // access member of base
    ob.show(); // access member of base
    ob.showk(); // uses member of derived class
    return 0;
}

答案 1 :(得分:1)

  

在Base类的函数set(int,int)中,我想调用派生类函数showK()。有没有办法做到这一点?我不能在类Base中声明showK()函数,我不能将其作为虚拟。这是对我的限制

如果您知道这是派生类的实例,那么您可以将强制转换为派生并调用该函数...

void Base:: set(int a, int b)
{ 
    i=a; j=b; 
    ((derived* const) this)->showk();
}

你总是可以做一个dynamic_cast来测试它是否是派生的,如果你想做一些不同的事情,如果它不是

(话虽如此,我建议如果你处于这种情况,那么你的设计可能会出现问题。一般来说,基类不应该“了解”他们的派生类。)

答案 2 :(得分:0)

template <class derived_type>
class Base{
    int i, j;
    public:
    void set( int, int );
    void show() { cout << i << " " << j << "\n"; }
};

template <class derived_type>
void Base<derived_type>:: set(int a, int b)
{ 
    i=a; j=b; 
    static_cast<derived_type*>(this)->showk();
}

class derived : public Base<derived> {
    int k;
    public:
    derived(int x) { k=x; }
    virtual void showk() { cout << k << "\n"; }
};

int main()
{
    derived ob(3);
    ob.set(1, 2); // access member of base
    ob.show(); // access member of base
    ob.showk(); // uses member of derived class
    return 0;
}

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern