虚函数与多态学习总结

匿名 (未验证) 提交于 2019-12-03 00:34:01

#include<iostream>

using namespace std ;

class Base

{ public :    

 Base(char xx)  { x = xx; }

 void who()  { cout <<"Base class: " << x << "\n" ; }

 protected:    char x;

} ;

class First_d : public  Base

{ public : 

    First_d(char xx, char yy):Base(xx) { y = yy; }

    void who()  { cout <<"First derived class: "<< x << ", " << y<< "\n" ; }

  protected:    char y;

} ;

class Second_d : public  First_d

{ public :

     Second_d( char xx, char yy, char zz ) : First_d( xx, yy ) { z = zz; }

     void who()  { cout <<"Second derived class: "<< x << ", " << y<< ", " << z << "\n" ; }

  protected:    char z;

} ;

int main()

{

Base  B_obj( 'A' ) ; 

 First_d F_obj( 'T', 'O' ) ;

 Second_d S_obj( 'E', 'N', 'D') ;

  Base  * p ;

  p = & B_obj ;    p -> who();

  p = &F_obj ;     p -> who();

  p = &S_obj ;     p -> who();

  F_obj.who() ;

  ( ( Second_d * ) p ) -> who() ;

}

class base

{ public :

     virtual  void  vf1 ( ) ;

     virtual  void  vf2 ( ) ;

     virtual  void  vf3 ( ) ;

     void  f ( ) ;

 };

class derived : public  base

{ public :

 };

#include<iostream>

using namespace std ;

class A

 };

class B : public A

} ;

int main() {

    A *Ap = new B ;

   B *Bp2 = new B ;

   cout << "delete first object:\n" ;

   delete Ap;

   cout << "delete second object:\n" ;

   delete Bp2 ;

}

#include <iostream.h>

class A

{ public:

  virtualdouble funA(double x)

 { cout<<"funA of class A called."<<endl;

     return x*x;  }

  doublefunB(double x)

  {   return funA(x)/2;   }

};

class B:public A

{  public:

   virtual double funA(double x)

 {  cout<<"funA of classB called."<<endl;

     return 2*x*x;  }

};

class C:public B

{  public:

 virtual double funA(double x)

 { cout<<"funA of class C called."<<endl;

     return 3*x*x;

  }

};

void main()

{

    C objc;

    cout<<objc.funB(3)<<endl;

    B objb;

    cout<<objb.funB(3)<<endl;

}

{ point center ;

 public :

 point  where ( ) { return  center ; }

 void  move ( point p ) {center = p; draw ( ) ; }

} ;

 


转载请标明出处:虚函数与多态学习总结
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!