c++中的虚函数

    今天碰到三个问题,现在来浅显地解答一下,算是回顾一下c++。

        问题1.什么是虚函数(virtual function)。

        问题2.虚函数怎么实现。

        问题3.使用虚函数有什么代价

=================================================================================

问题1.

    虚函数是指在继承类中可以被重新定义的成员函数,并且保留被调用的属性(纯虚函数不可以调用)。声明虚函数只要在一般的函数前面加上关键字 virtual。

问题2.

    这个问题回答起来有些复杂。

    首先,实现一个简单的虚函数。

#include <iostream>
using namespace std;
 
class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()
      { return 0; }
};
 
class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
};
 
class Triangle: public Polygon {
  public:
    int area ()
      { return (width * height / 2); }
};
 
int main () {
  Rectangle rect;
  Triangle trgl;
  Polygon poly;
  Polygon * ppoly1 = ▭
  Polygon * ppoly2 = &trgl;
  Polygon * ppoly3 = &poly;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  ppoly3->set_values (4,5);
  cout << ppoly1->area() << '\n';
  cout << ppoly2->area() << '\n';
  cout << ppoly3->area() << '\n';
  return 0;
}
 
20;
10;
0;
下面,实现一个纯虚函数。包含纯虚函数的类属于抽象类。

#include <iostream>
using namespace std;
 
class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
};
 
class Rectangle: public Polygon {
  public:
    int area (void)
      { return (width * height); }
};
 
class Triangle: public Polygon {
  public:
    int area (void)
      { return (width * height / 2); }
};
 
int main () {
  Rectangle rect;
  Triangle trgl;
  Polygon * ppoly1 = ▭
  Polygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  cout << ppoly1->area() << '\n';
  cout << ppoly2->area() << '\n';
  return 0;
}
 
10;
20;

说明:在基类class Polygon中,定义了纯虚函数 virtual int area()=0。

此时 class Ploygon 不能定义定义对象(抽象类不能定义对象)。

Polygon myPolygon;    // 定义非法
不过可以这样定义(定义指针)。
Ploygon *ploygon1;
Ploygon *ploygon2;
这时便可以实现c++中的多态了:将基类(Polygon)指针赋予不同继承类的对象的地址。

Rectangle rect;
Triangle trgl;
polygon1 = ▭
polygon2 = &trgl;
虚函数area()会根据调用者的不同实现不同的功能。

polygon1->area();   // rectangular 类中的area() 起作用
polygon2->area();   // triangle 类中的area() 起作用

问题3.

    这个问题比较高深,可以参考

 

    http://www.cppblog.com/woaidongmao/archive/2008/05/22/50806.html

    感谢这位作者的辛苦工作!







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值