C++ 虚函数

         在类成员函数前加关键字virtual,则该函数为虚函数。

   虚函数的使用格式;

class A

{

public:

   virtual void show();


}

说明;
 1,当在派生类中定义了一个同名的成员函数时,只要该函数的参数个数和相关类型以及返回值与基类中的同名的虚函数完全一样,则      无论是否为该成员 函数说明为虚函数,它都将成为一个虚函数。
2.使用虚函数保证了在通过一个基类类型的指针(包含引用 )调用一个虚函数时,系统会进行动态调用 派生类的函数。使基类的作用域变大 了。这就是多态。
3,如果在派生类中没有对基类的虚函数进重新实现,则它继承的是基类中的虚函数。
4,如果一个类要作为基类派生其他子类,尽可能使用虚函数。用多态的时候可以用,光继承的话可以不用。
5,在使用虚函数时,可以使用成员名限定强制使用基类函数。   cout<<p->Shape::area()<<endl;//限定调用基类的函数


#ifndef _______Shape__

#define _______Shape__


#include <iostream>

class Shape

{

private:

    int x;

    int y;

public:

    void setX(int _x,int _y);

    int getX();

    int getY();

    virtual float area();//加上virtual,基类可以调用派生类的函数。

};


#endif /* defined(_______Shape__) */




#include "Shape.h"

void Shape::setX(int _x, int _y)

{

    x=_x;

    y=_y;

}

int Shape::getX()

{

    return x;

}

int Shape::getY()

{

    return y;

    

}


float Shape::area()//只是图形,不知道具体的图形,所以面积写不出来,所以return 0

{

    return 0;

}



#ifndef _______Rectangle__

#define _______Rectangle__


#include <iostream>

#include "Shape.h"

class Rectangle :public Shape

{

private:

    int width;

    int height;

public:

    void setWH(int _w,int _h);

    int getWidth();

    int getHeigth();

    float area();    

};


#endif /* defined(_______Rectangle__) */



#include "Rectangle.h"

void Rectangle::setWH(int _w, int _h)

{

    width=_w;

    height=_h;

}

int Rectangle:: getWidth()

{

    return width;

}

int Rectangle::getHeigth()

{

    return height;

}

float Rectangle:: area()

{

    return width*height;

}





#include <iostream>

#include "Rectangle.h"

#include "Shape.h"

using namespace std;


int main(int argc, const char * argv[])

{


    Shape *p;

    Rectangle rect;

    rect.setWH(10, 20);

    p=&rect;

    cout<<p->area()<<endl;//调用派生类的函数,实现多态5

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

    

    

    

    

    

    return 0;

}


注意:在使用虚函数时,可以使用成员名限定强制使用基类函数。

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值