首页 > 解决方案 > 函数从唯一代码调用正确的子类方法

问题描述

我想使用一个通用函数来调用子类的正确方法

这是我在 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  
*/

标签: c++structsubclassing

解决方案


虚拟成功了。我非常接近,但现在它可以工作了

谢谢伊戈尔

回答我的问题以供将来参考

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 
*/

推荐阅读