转自:http://blog.csdn.net/liuzhanchen1987/article/details/8074714
- <pre class="cpp" name="code">#include<iostream>
- using namespace std;
- class A
- {
- public:
- virtual void fun1()
- {
- cout<<"A fun1"<<endl;
- }
- void fun2()
- {
- cout<<"A fun2"<<endl;
- }
- };
- class B :public A
- {
- public:
- void fun1()
- {
- cout<<"B fun1"<<endl;
- }
- void fun2()
- {
- cout<<"B fun2"<<endl;
- }
- };
- int main()
- {
- B *obB=new B;
- A *obA=(A*)obB;
- obA->fun1();
- obA->fun2();
- cout<<endl;
- obA = (B*)obA;
- obA->fun1();
- obA->fun2();cout<<endl;
- A *a1=new A;
- B *b1=(B*)a1;
- a1->fun1();
- a1->fun2();cout<<endl;
- a1=(A*)a1;
- a1->fun1();
- a1->fun2();
- cout<<endl;
- B b2;
- A a2=b2;//对象类型进行了转换
- a2.fun1();
- a2.fun2();cout<<endl;
- A a3;
- // B b3=(B)a3; 不可以转换
- return 0;
- }</pre><br>
- <pre><pre class="cpp" name="code">对于多态,调用子类的函数还是父类的函数是由其对象决定的,不是由指针决定的,
- 输出结果是:</pre><pre class="cpp" name="code">B fun1
- A fun2</pre><pre class="cpp" name="code">父类指针指向子类,如果父类函数为虚函数则调用子函数,否则调用父类中函数。 B fun1
- A fun2</pre><pre class="cpp" name="code">将原先指向子类的父类再转换成子类,不太清楚为什么是以上输出,欢迎大牛指点派生类指针指向基类,调用的函数全是基类的,因为该对象没有被转换成派生类对象A fun1
- A fun2</pre><pre class="cpp" name="code">A fun1
- A fun2</pre><pre class="cpp" name="code">派生类完全转换成基类对象</pre><pre class="cpp" name="code">A fun1</pre><pre class="cpp" name="code">A fun2</pre><br></pre>
- <pre></pre>