在下面的代码中,在 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/