转载于http://blog.csdn.net/chhuach2005/article/details/40322895
1) 覆盖 重载 隐藏
覆盖:基类定义的虚函数,派生类中重新定义,派生类的虚函数表将覆盖基类已定义的虚函数。
重载:重载发生在同一个类中,重载不能跨类。重载是因为函数名相同,函数的参数个数或参数的类型不同,而调用相应的函数。
隐藏:这个,以前没怎么注意。隐藏发生在派生类中有何基类同名的虚函数时,此时基类中的同名重载函数不被继承到派生类。
代码说明如下:
- class Base//基类中fun1有3个函数,是重载
- {
- public:
- virtual void fun1(int a)
- {
- cout<<"Base fun1 int "<<a<<endl;
- }
- virtual void fun1(double a)
- {
- cout<<"Base fun1 double "<<a<<endl;
- }
- void fun1()
- {
- cout<<"Base fun1 () "<<5<<endl;
- }
- };
- class Derive:public Base // 显然派生类中的fun1(int a)是基类的fun1(int a)的重写
- {
- public:
- virtual void fun1(int a)
- {
- cout<<"Derive fun1 int "<<a<<endl;
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- Base *p=new Derive;//隐藏的函数,用指针可以调用,隐藏和多态同时出现时,隐藏优先级高
- p->fun1(3.3);//由于隐藏优先级高,此处用基类指针调用fun1(3.3),不会发生多态,调用的是基类的fun1(3.3),在基类又会产生重载。
- p->fun1(3); //多态调用派生类中的函数
- p->fun1(); //同理会调用基类的fun1()函数,在基类会有重载。
- Derive *p1=new Derive;
- p1->fun1(3.3);//因为派生类没有继承fun1(double),因此fun1(3.3)会调用fun1(int)
- //p1->fun1();//由于fun1()未被继承到派生类中,本行调用若不注释,会出错编译不通过。
- Base *p2=new Base;
- p2->fun1(3.3);
- system("pause");
- return 0 ;
- }
运行结果:
结果如图1所示,与以上分析相同
图1 重载、覆盖、隐藏
2) 类变量的声明与执行顺序
且看以下代码
- class A
- {
- public:
- A()
- {
- cout<<"A is called"<<endl;
- }
- };
- class B
- {
- public:
- B()
- {
- cout<<"B is called"<<endl;
- }
- };
- class C
- {
- public:
- C()
- {
- cout<<"C is called"<<endl;
- }
- };
- class D
- {
- public:
- D()
- {
- cout<<"D is called"<<endl;
- }
- };
- void test()
- {
- static C c;
- D d;
- }
- A a;
- int _tmain(int argc, _TCHAR* argv[])
- {
- test();
- system("pause");
- return 0 ;
- }
- B b;
你觉得构造的顺序到底是怎样的呢?是main()函数体先执行还是b先构造呢?
执行结果为图2,从图2中可以看出,是先构造类的全局变量的,哪怕它在main函数之后,在main函数里的类变量构造是按类变量的定义顺序构造的。
图2 类变量的构造顺序
3) Main函数能递归吗
- int main()
- {
- static int n=5;
- cout<<n<<endl;
- n--;
- if (n==0)
- {
- system("pause");
- return 0 ;
- }
- main();
- }
实际测试是可以递归的 运行结果如下:
图3 main()递归