在下面的代码中,在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;
}
提前致谢。