039-C++多态

#include <iostream>

using namespace std;

/**
 * C++中的动态是通过virtual关键字来实现的 如果不使用virtual 即使派生类重写父类方法,最后在运行时还是会执行
 * 父类的方法,这种情况属于静态绑定。如果使用了virtual 则在运行时会调用派生类重写的父类方法,这种情况叫做动态
 * 绑定。
 * 使用virtual 关键字,但是有实现的方法称为虚函数
 * 使用virtual 关键字,但是没有实现 并且格式是 virtual return_type method_name() = 0 的这种方法称为纯虚函数
*/

class Shape {
    protected:
        int width, height;

    public:
        Shape(int a = 0, int b = 0) {
            width = a;
            height = b;
        }   

        // 虚函数
        virtual int getArea() {
          cout<<"invoke parent class"<<endl;
          return 0;
        } 
        // 纯虚函数
        virtual char* getColor()=0;

};

class Rectangle: public Shape {
    
    public:
       Rectangle(int a=0, int b=0):Shape(a, b){}
       int getArea() {
          cout<<"Rectangl area is: "<<endl;
          return (width*height);
       } 
       char* getColor(){
           return "red";
       }
};

class Triangle: public Shape {
     public:
        Triangle(int a =0, int b = 0):Shape(a, b){}
        int getArea() {
            cout<<"Triangle area is: "<<endl; 
            return (width*height)/2;
        }
        char* getColor(){
            return "blue";
        }
};


int main(int argc, char const *argv[])
{
  /* code */
  Shape *shape;
  Rectangle rect(10, 20);
  Triangle triangle(10, 20);
  shape = &rect;
  int rectArea = shape->getArea();
  cout<<"rectangle area is: "<<rectArea<<" color is "<<shape->getColor()<<endl;
  shape = &triangle;
  int triangleArea = shape->getArea();
  cout<<"triangle area is: "<<triangleArea<<" color is "<<shape->getColor()<<endl;
  return 0;
}

输出如下:

Rectangl area is: 
rectangle area is: 200 color is red
Triangle area is: 
triangle area is: 100 color is blue

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值