从使用派生类的成员函数的基类调用函数

时间:2017-05-14 10:20:59

标签: c++11 inheritance visual-c++ member-functions

我创建了一个几乎完全相同的类和派生类。 唯一的区别是派生类有2个不同的函数和3个额外的变量。我希望B类中的被调用函数使用继承的函数,但是使用类B的PrivFunctions。相反,当调用时,函数使用他自己的类A类的PrivFunction。

var result = [],
    inputA = [].concat(Alevels),
    inputB = [].concat(Degrees);

while (inputA.length > 0) {

  result.push(
    //first three items (removed) of Array A
    inputA.splice(0,3)
     //combine with
     .concat(
       //first item (removed) of Array B
       [inputB.shift()]
       //join together
     ).join(' '));
}

我已经考虑过在Function()中添加私有函数的地址,但这看起来太过分了。我觉得我错过了一些简单的东西,但我无法找到如何做到这一点整洁

1 个答案:

答案 0 :(得分:0)

您需要做的是将基类中的函数声明为virtual。这是您在基类A中定义的一种函数,然后需要在子类中重新定义。将函数声明为virtual可确保调用正确的函数并避免歧义。

你的代码应该是这样的:

class A
{
     protected:
     double x, y, z;
     //define as virtual
     virtual Function(){/*do something*/}

     /*
     rest of your code
     */
}
class B: public A
{
    private:
    double a, b, c

    public:
    //redefine your function in the subclass
    Function(){/*do something else*/}
    /*
    rest of your code
    */
}
int main()
{
    B classb();
    //This will now use B's Function
    classb.Function();
}
相关问题