c++ - 函数从唯一代码调用正确的子类方法
问题描述
我想使用一个通用函数来调用子类的正确方法
这是我在 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
*/
推荐阅读
- c# - 如何使用 Postman 上的 POST 请求将数据插入到多个表中?
- python - 如何读取多个文件并找到文件之间的差异?
- excel - 将函数参数更改为变体后的“运行时错误 424:需要对象”
- c# - 循环中 EventTrigger 的意外结果
- ios - 不是在登录时记录用户的坐标(双精度),而是位置委托如何在移动时检查位置?
- ms-word - 如何从word模板中的字段生成条形码?
- r - R - 闪亮的`observeEvent`之后的`reactive`
- python - 在 Raspberry Pi 上的 Python 代码中隐藏数据库凭据
- amazon-web-services - 无法使用 ansible playbook 删除 AWS VPC
- assembly - 构建最少的汇编代码会产生空的二进制文件