我想使用一个泛型函数来调用子类的适当方法
这是我在C ++中发现的一个问题,通常可以使用其他OOP语言(CLOS,python)解决,但我对C ++的了解不足以解决此问题。
这是一个注释的代码:我不知道如何在C ++中解决这个问题谢谢
#include <memory>
#include <cstdlib>
struct s_A
{
// virtual ~A() {}
int numFunct()
{
printf("\n... running s_A method");
// basic behaviour
return 10;
}
};
struct s_B : s_A
{
int numFunct()
{
printf("\n... running s_B method");
// customized behaviour for s_B instances here
return 20;
}
};
struct s_C : s_A
{
int numFunct()
{
printf("\n... running s_C method");
// customized behaviour for s_C instances here
return 30;
}
};
// want to code a unique giveIntanceNum function but with personalized behavior
// depending on the type of the argument
// I guess the problem is in argument declaration ?
int giveIntanceNum(s_A * myInstance)
{
// ...
// code here is long enough not to be recoded for every customized subclass
// ....
return myInstance->numFunct();
}
int main() //testing
{
s_B * B = new s_B;
s_C * C = new s_C;
printf("\nReturned values calling method directly are %d and %d ", B->numFunct(), C->numFunct());
printf("\nReturned values calling through function are %d and %d ", giveIntanceNum(B), giveIntanceNum(C));
// I would like to get 20 for B and 30 for C as numFunct is called for a B (C) instance not an A
}
/* OUTPUT
... running s_C method
... running s_B method
Returned values calling method directly are 20 and 30
... running s_A method
... running s_A method
Returned values calling through function are 10 and 10
*/
虚拟的把戏。我离得很近,但是现在可以了
感谢伊戈尔
回答我的问题以备将来参考
struct s_A
{
// virtual ~A() {}
virtual int numFunct()
{
printf("\n... running s_A method");
return 10;
}
};
...
/* OUTPUT
... running s_C method
... running s_B method
Returned values calling method directly are 20 and 30
... running s_C method
... running s_B method
Returned values calling through function are 20 and 30
*/