简体   繁体   English

来自多个类的c ++多态

[英]c++ polymorphism from multiple classes

Is there anyway to do a type of "stacking inheritance" where you replace potentially multiple functions of a base class based on other calls? 反正有没有做一种“堆叠继承”,你可以根据其他调用替换基类的潜在多个函数?

for example something like: 例如:

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()
}

Thank you 谢谢

There are virtual functions and multiple inheritance (which should be avoided if possible) in C++. 在C ++中有虚函数和多继承(如果可能,应该避免)。

What you could do in this case is: 在这种情况下你可以做的是:

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()
}

you could even skip instantiating the Base object and just do 你甚至可以跳过实例化Base对象而只是这样做

int main(){
   A2 obj;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM