c++ - 从基类函数调用派生类函数

标签 c++ inheritance virtual

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

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

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;
}

提前致谢。

最佳答案

In the function set(int, int) of class Base, I want to call the derived class function showK(). Is there a way to do this? I can not declare showK() function in class Base and i can not make that as virtual. This is a restriction for me

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

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

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

(话虽如此,我建议如果您处于这种情况,那么您的设计可能有问题。一般来说,基类不应该“知道”它们的派生类。)

关于c++ - 从基类函数调用派生类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10028591/

相关文章:

c++ - 在哪里可以找到当前的 C 或 C++ 标准文档?

c++ - 为什么模板只能在头文件中实现?

c++ - 什么是 diff b/w Includes in VC++ Directories options 和 Additional include directories in C++ -> General in Visual Studio

c++ - 异常继承

python - 在 Python 中,有什么方法可以从其父类调用子类的方法重写吗?

C++:如何将对象传递给函数作为模板化基类

c# - 在基类中将 ToString 标记为虚拟,会发生什么?

c++ - 对 vtable 的 undefined reference - 虚拟成员,由 gsoap 生成的类

directory - Azure Web 角色中的虚拟目录

php - USB key 中的Linux测试环境(apache + php + git)?