来自多个类的c ++多态

时间:2017-08-29 12:51:23

标签: c++ inheritance polymorphism multiple-inheritance

有没有做一种“堆叠继承”,你可以根据其他调用替换基类的潜在多个函数?

例如:

class Base {
      void func1(){/* do something */}
      void func2(){/* do something */}
};
class A1 {
      void func1(){/* do something else */}
};
class A2 {
      void func2(){/* do something else */}
};

int main(){
   A1 a1obj = new A1();
   A2 a2obj = new A2();
   Base obj = new Base();

   obj = &a1obj;
   obj = &a2obj;
   obj.func1(); //now A1::func1()
   obj.func2(); //now A2::func2()
}

谢谢

1 个答案:

答案 0 :(得分:2)

在C ++中有虚函数和多重继承(如果可能,应该避免)。

在这种情况下你可以做的是:

class Base {
      virtual void func1(){/* do something */}
      virtual void func2(){/* do something */}
};
class A1: public Base {
      void func1() override {/* do something else */}
};
class A2: public A1 {
      void func2() override {/* do something else */}
};

int main(){
   A2 a2obj;
   Base* obj = &a2obj;

   obj->func1(); //now A1::func1()
   obj->func2(); //now A2::func2()
}

你甚至可以跳过实例化Base对象而只是做

int main(){
   A2 obj;

   obj.func1(); //now A1::func1()
   obj.func2(); //now A2::func2()
}