类继承
★ 对于父类函数(virtual、非virtual),如果子类没有同名函数,则正常继承
★ 对于父类函数(virtual、非virtual),如果子类有同名函数,无同型函数,则不能调用父类函数
★ 对于父类函数(virtual、非virtual),如果有同型函数:
----非virtual函数由指针类型决定调用哪个
----virtual函数由指针指向的对象决定调用哪个(运行时决定)
1 //如果对于父类函数(virtual/非virtual),如果子类没有同名函数,则正常继承 2 3 class Base 4 5 { 6 7public: void func(int i){ cout <<"Base::func(int)"<< endl; } 8 9}; 1011 1213class Derived : public Base1415{ }; 1617 1819int main()2021{ 2223 Base *pb = new Derived();2425 pb->func(1); //Base::func(int)2627 delete pb; 2829 3031 Derived *pd = new Derived();3233 pd->func(1); //Base::func(int)3435 delete pd; 3637}
1 //对于父类函数(virtual、非virutal),子类有同名函数,无同型函数,则不能调用父类函数 2 3 class Base 4 5 { 6 7public: 8 9 void func(int i){ cout <<"Base::func(int i)"<< endl; } 1011 virtual void func2(int i) { cout << "Base::func2(int i)" << endl;}1213}; 1415 1617class Derived : public Base1819{ 2021public: 2223 void func(){ cout <<"Derived::func()"<< endl; } 2425 void func2(){ cout <<"Derived::func2()"<< endl; } 2627}; 2829 3031int main()3233{ 3435 Base *pb = new Derived();3637 pb->func(1); //Base::func(int)3839 pb->func2(1); //Base::func2(int i)4041 delete pb; 4243 4445 Derived *pd = new Derived();4647 pd->func(); //Derived::func()4849 pd->func2(); //Derived::func2()5051 // pd->func2(1); //不能调用 5253 delete pd; 5455}
1 //对于父类函数(virtual、非virtual),如果有同型函数: 2 3 //----非virtual函数由指针类型决定调用哪个 4 5 //----virtual函数由指针指向的对象决定调用哪个(运行时决定) 6 7 class Base 8 9 { public:1011 void func(int i){ cout <<"Base::func(int i)"<< endl; }1213 void func() {cout << "Base::func() " << endl;}1415 virtual void func2(int i) { cout << "Base::func2(int i)" << endl;}1617}; 1819 2021class Derived : public Base2223{ public: 2425 void func(int i){ cout <<"Derived::func()"<< endl; } 2627 void func2(int i){ cout <<"Derived::func2(int i)"<< endl; } 2829}; 3031 3233int main()3435{ 3637 Base *pb = new Derived();3839 pb->func(1); //Base::func(int i)4041 pb->func(); //Base:func()4243 pb->func2(1); //Derived::func2(int i)4445 delete pb; 4647 4849 Derived *pd = new Derived();5051 pd->func(1); //Derived::func(int i)5253 // pd->func(); //不能调用 5455 pd->func2(1); //Derived::func2(int i)5657 delete pd;5859}