C++之纯虚函数和抽象类

文章目录

纯虚函数

  • 如果一个虚函数仅表达抽象的行为,没有具体的功能,即只有声明没有定义,这样的虚函数被称为纯虚函数或抽象方法
cpp 复制代码
class 类名 {
public:
    virtual 返回类型 函数名 (形参表) = 0;
};
  • 假设有图形类Figure, 设计计算面积的成员函数area()
  • Figure只是一个纯抽象意义上得概念,不存在计算面积或体积的具体方法,所以只能将成员函数area()设计为纯虚函数
cpp 复制代码
#include <iostream>
using namespace std;
class Figure{
protected:
    double x, y;
public:
    void set(double i, double j){
        x = i;
        y = j;
    }
    virtual void area()=0;
};

抽象类

  • 如果类中包含了纯虚函数,那么这个类就是抽象类
  • 抽象类只能最为其它类的基类,不能用来建立对象
  • 如果类中的所有成员函数都是纯虚函数则可以称为纯抽象类
cpp 复制代码
#include <iostream>
using namespace std;
class Shape{
public:
    virtual void draw(void) = 0;
};
class Rect:public Shape{
public:
    void draw(void){
        cout << "draw Rect" << endl;
    }
};
class Circle: public Shape{
public:
    void draw(void){
        cout << "draw Circle" << endl;
    }
};
class Ellipse: public Shape{
public:
    void draw(void){
        cout << "draw Ellipse" << endl;
    }
};
int main(void){
    /*
    Ellipse e;
    e.draw();
    e.Shape::draw();
    */
    //Shape s1; //error
    Shape *buf[128] = {0};
    buf[0] = new Rect;
    buf[1] = new Circle;
    buf[2] = new Ellipse;
    for(int i=0; buf[i] != NULL; i++){
        buf[i]->draw();
    }
    return 0;
}
相关推荐
blasit2 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_3 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛5 天前
delete又未完全delete
c++
端平入洛6 天前
auto有时不auto
c++
哇哈哈20217 天前
信号量和信号
linux·c++
多恩Stone7 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马7 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝7 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc7 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法