一个类可以继承至多个基类(也就是多继承,Java不行)
class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); } };
class D{......}; class B: public D{......}; class A: public D{......}; class C: public B, public A{.....};
这样在C c时,会新建两个D对象,即D(), B(), D(), A(), C().
使用虚拟继承解决此问题:
class D{......}; class B: virtual public D{......}; class A: virtual public D{......}; class C: public B, public A{.....};只会执行D(), B(), A(), C().
比如想调用父类A中的方法,可以使用:
c.A::test();
#include <stdio.h> #include <iostream> #include <windows.h> #include <time.h> using namespace std; class A { public: void test(){ cout << "A test()" << endl; }; }; class B { public: boolean test(B b){ cout << "B test()" << endl; return false; }; }; class C:public A, public B{ public: void test(){ cout << "C test()" << endl; } }; int main() { C c; c.A::test();//A test() system("pause"); return 0; }同名函数的形参(参数的个数、类型或者顺序)不同
重载运算符 Box operator+(const Box& b) { Box box; box.length = this->length + b.length; return box; } box3 = box1 + box2; //即box3的box3.length=box1.length+box2.length