How to inherit from a class that implement an interface which is shared with other interface
我有这个示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> struct Interface1 { virtual int getID()=0; }; struct Interface2 : Interface1 { virtual int add(int a,int b)=0; }; struct Base1 : Interface1 { virtual int getID() override { return 1; } }; struct myClass: Interface2, Base1 { virtual int add(int a,int b) override { return a+b; } }; int main() { myClass c; std::cout << c.add(0, 1) <<" "; } |
其思想是,
1 | getId is ambiguous. |
我怎么修?
问题是,
解决方案(除了使用更简单的继承)是使类实际上从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> struct Interface1 { virtual int getID()=0; }; struct Interface2 : virtual Interface1 { virtual int add(int a,int b)=0; }; struct Base1 : virtual Interface1 { virtual int getID() override { return 1; } }; struct myClass: Interface2, Base1 { virtual int add(int a,int b) override { return a+b; } }; int main() { myClass c; std::cout << c.getID() <<" "; // prints 1 } |