超简单!c++虚函数例子解析

#include <iostream>
using namespace std;
class Shape
{
public:    //普通函数前加virtual,普通函数变成了虚函数  // =0表示抽象虚函数,子类必须实现该函数
    virtual void printarea()=0;
    void hello(){cout<<"Shape hello function"<<endl;};
};
class Circle:public Shape
{
public:
    Circle(int a):r(a){}
    void hello(){cout<<"Circle hello function"<<endl;};
    void printarea(){cout<<"圆形面积为:"<<r*r*3.14<<endl;}
private:
    int r;
};
class Rectangle:public Shape
{
public:
    Rectangle(int a,int b):x(a),y(b){}
    void hello(){cout<<"Rectangle hello function"<<endl;};
    void printarea(){cout<<"矩形面积为:"<<x*y<<endl;}
private:
    int x;
    int y;
};
class Square:public Shape
{
public:
    Square(int a):l(a){}
    void hello(){cout<<"Square hello function"<<endl;};

    void printarea(){cout<<"正方形面积为:"<<l*l<<endl;}
private:
    int l;
};

void prints(Shape *s) {  //基类指针s指向子类对象   //s调用的函数printarea是虚函数,所以会调用子类实例的printarea
    s->printarea();   //s调用的函数hello不是虚函数,所以只会调用基类的hello
    s->hello();
}

int main()
{
    Circle a(1);
    prints(&a);
    Square b(2);
    prints(&b);
    Rectangle c(1,2);
    prints(&c);
    return 0;
}

输出:

圆形面积为:3.14
Shape hello function
正方形面积为:4
Shape hello function
矩形面积为:2
Shape hello function

原文链接: https://www.cnblogs.com/zhengze/p/12624793.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/195282

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:56
下一篇 2023年2月12日 下午6:56

相关推荐