c++多态

来源:互联网 发布:博时银联大数据 编辑:程序博客网 时间:2024/06/10 16:52

 多态:

          一个接口,多个内在实现。在c++中,多态是指:相同的代码,可以根据运行情况的不同,而执行不同的操作,c++中支持两种多态性:编译时的多态性运行时多态性

             编译时的多态性也叫做静态联编,是能过重载函数来实现的

             运行时的多态性也叫动态联编,是通过继承过程中的虚函数的使用来实现的。

《静态联编》

         编译时的多态性,主要是通过重载函数来实现的,重载函数是指:函数名相同,参数列表不同的函数,对于类来说,重载函数发生在同一个类里面。

#include <iostream>

using namespacestd;

class point

{

private:

   float x;

   float y;

public:

   void setXY(float _x,float _y)

    {

       x=_x;

       y=_y;

    }

   float getX()

    {

       returnx;

    }

   float getY()

    {

       returny;

    }

   float area()

    {

       return0;

    }

    

  };


class Square:publicpoint

{

private:

   float iLength;

public:

   void setLength(float _L)

    {

       iLength=_L;

    }

    

   float getLength()

    {

       returniLength;

    }

   float area()

    {

        returniLength*iLength;

    }

    

    

    

};



int main(int argc,constchar * argv[])

{


   point pointobj;

   float iArea=pointobj.area();

   cout<<iArea<<endl;

   Square squobj;

    squobj.setLength(4.5);

    iArea=squobj.area();

   cout<<iArea<<endl;

    

    

    

    

    

   return0;

}


       程序分析:由于点的面积和求正方形的面积算法是不同的, 所以在派生类正方形中,我们重新实现了函数area().这样当需要求正方形面积时,调用它本身的area()函数便可以得出正确的结果。

《动态联编》

#include <iostream>

using namespacestd;

class point

{

private:

   float x;

   float y;

public:

   void setXY(float _x,float _y)

    {

       x=_x;

       y=_y;

    }

   float getX()

    {

       return x;

    }

   float getY()

    {

       return y;

    }

  virtual  float area()

    {

       return 0;

    }

    

  };


class Square:publicpoint

{

private:

   float iLength;

public:

   void setLength(float _L)

    {

       iLength=_L;

    }

    

   float getLength()

    {

       return iLength;

    }

   float area()

    {

        returniLength*iLength;

    }

    

    

    

};



int main(int argc,constchar * argv[])

{


   point *pointobj;

    Square squobj;

    pointobj=&squobj;//加上virtual,基类可以调用派生类的函数。

    squobj.setLength(4.5);

   float iArea=pointobj->area();//调用派生类的函数,实现多态5

   cout<<iArea<<endl;

    

   cout<<pointobj->area()<<endl;

    

   cout<<pointobj->point::area()<<endl;////使用成员名限定强制使用基类函数

    

    

    

    

   return 0;

}


程序分析:

        在程序中,我们是将一个派生类的对象地址赋值给一个基类的指针,当基类的指针指向派生类的对象时,基类的指针只能访问派生类对象从基类继承下来的成员。pointobj->area()时,调用的是从Point类继承下来的area()函数,而不是square类本身的area()函数。

这时 的输出结果,显然不是我们想要的,而我们想要的是square类的面积,这时可以将关键字virtual放在基类中的area函数说明前面,实现动态调用。

        关键字virtual指示C++编译器,在运行时才确定pintobj->area()所调用的函数是派生类的。


原创粉丝点击