virtual实现C++运行时多态

#include<stdio.h>
class Shape{
public:
    Shape(int width,int height):mWidth(width),mHeight(height){
        printf("shape constructor\n");
    }
    long getArea(){
        printf("shape getArea,width=%d,height=%d\n",mWidth,mHeight);
        return 0;
    }

int mWidth,mHeight;
};
class Rectangle:public Shape{
public:
     Rectangle(int width,int height):Shape(width,height){
        printf("rectangle constructor\n");
    }
    long getArea(){
        printf("rectangle getArea,width=%d,height=%d\n",mWidth,mHeight);
        return 0;
    }

};
void function(Shape *shape){
    shape->getArea();
}
int main(){
    Shape shape(1,2);
    Rectangle rectangle(3,4);
    function(&shape);
    function(&rectangle);
}

log打印:

shape constructor

shape constructor

rectangle constructor

shape getArea,width=1,height=2

shape getArea,width=3,height=4

virtual关键字作用于函数动态绑定,可以实现C++的运行时多态

#include<stdio.h>
class Shape{
public:
    Shape(int width,int height):mWidth(width),mHeight(height){
        printf("shape constructor\n");
    }
    virtual long getArea();

    int mWidth,mHeight;
};
long Shape::getArea(){
        printf("shape getArea,width=%d,height=%d\n",mWidth,mHeight);
        return 0;
}

class Rectangle:public Shape{
public:
     Rectangle(int width,int height,int count):Shape(width,height),mCount(count){
        printf("rectangle constructor,mcount=%d\n",mCount);
    }
    virtual long getArea();
private:
    int mCount;
};
long Rectangle::getArea(){
    printf("rectangle getArea,width=%d,height=%d\n",mWidth,mHeight);
    return 0;
}

void function(Shape *shape){
    shape->getArea();
}
int main(){
    Shape shape(1,2);
    Rectangle rectangle(3,4,1);
    function(&shape);
    function(&rectangle);
}

gcc virtual_method.cpp -fno-rtti编译后运行log打印:

shape constructor

shape constructor

rectangle constructor,mcount=1

shape getArea,width=1,height=2

rectangle getArea,width=3,height=4

注意:

  • 一般成员函数可以是虚函数
  • 构造函数不能是虚函数
  • 析构函数可以是虚函数(多态基类应该声明virtual析构函数,否则通过基类去析构派生类成员会导致析构不彻底,引起内存泄漏)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值