• C++ -抽象类和纯虚函数


     1 #include<iostream>
     2 #include<math.h>
     3 using namespace std;
     4 class Shape{
     5 public:
     6     virtual double Area()=0;
     7 };
     8 class Triangle:public Shape{
     9     double a,b,c;
    10 public:
    11     Triangle(double e1,double e2,double e3){
    12         a = e1;
    13         b = e2;
    14         c = e3;
    15     }
    16     double Area(){
    17         double s = 0.5*(a+b+c);
    18         return sqrt(s*(s-a)*(s-b)*(s-c));
    19     }
    20 };
    21 class Rectangle:public Shape{
    22     double a,b;
    23 public:
    24     Rectangle(double e1,double e2){
    25         a = e1;
    26         b = e2;
    27     }
    28     double Area(){
    29         return a*b;
    30     }
    31 };
    32 class Cricle:public Shape{
    33 public:
    34     double Shape::Area(){
    35     
    36     }//显式重写,意义与覆盖相同
    37 };
    38 int main(){
    39     Shape *p;
    40     Triangle t(3.0,4.0,5.0);
    41     Rectangle r(3.0,4.0);
    42     //虽然p是父类指针,因为有virtual ,所以会根据实际对象调用方法。
    43     p = &t;
    44     cout<<"The area of triangle is :"<<p->Area()<<endl;
    45     p = &r;
    46     cout<<"The area of rectangle is :"<<p->Area()<<endl;
    47 }
    48 /*
    49     纯虚函数:是一个只声明而不定义的函数。
    50     virtual type funcname(prara-list)=0;
    51     纯虚函数是一个没有定义的函数,所以包含该函数的类
    52     不能被实例化,它只能留到派生类中去实现,
    53     所以该类为抽象类。
    54 
    55     1、只有虚函数才能够只声明而不实现。
    56     2、如果派生类没有实现纯虚函数的覆盖,则派生类也属于抽象类
    57     3.其实抽象类的含义指:不能实例化的类,这种类包含两种:
    58     一种是里面含有纯虚函数
    59     第二种是构造函数的访问权限定义为private或protected
    60     4、一般抽象类作为公共的根。
    61     5、虽然抽象类不能被实例化,但是仍然可以定义抽象类的指针(或引用),
    62     该指针(或引用)指向派生类的对象。
    63 */
  • 相关阅读:
    LeetCode——37. 解数独
    LeetCode ——42. 接雨水
    异常
    IO/FILE
    函数与模块
    选择与循环
    运算符
    字符串、列表、元组等
    SVTyper
    Error:Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-not69mld/pysam/
  • 原文地址:https://www.cnblogs.com/teng-IT/p/6027124.html
Copyright © 2020-2023  润新知