C++学习笔记6:抽象类(接口)

纯虚函数与抽象类

纯虚函数

在之前的笔记中我们认识了虚函数,那么什么是纯虚函数呢?

纯虚函数是指对于一个虚函数只有声明而其函数体=0。因此,纯虚函数不需要实现,由子类继承后在子类中实现其具体功能。

抽象类

抽象类,又称抽象基类,是指拥有纯虚函数的类,抽象类只能作为基类,不能构建对象,因为抽象类中的纯虚函数没有函数体。

如果在程序中对抽象基类构建对象,那么则会出现报错,具体为下面的示例:

#include <iostream>
using namespace std;

class CBase{
    public:
    virtual void SomeVirtualFunction()=0;

};

int main(){
    CBase cb;
    return 0;
}

在终端中输入编译指令则会出现以下报错:

.\virtual.cpp:11:11: error: cannot declare variable 'cb' to be of abstract type 'CBase'
     CBase cb;
           ^~
.\virtual.cpp:4:7: note:   because the following virtual functions are pure within 'CBase':
 class CBase{
       ^~~~~
.\virtual.cpp:6:18: note:      'virtual void CBase::SomeVirtualFunction()'
     virtual void SomeVirtualFunction()=0;
                  ^~~~~~~~~~~~~~~~~~~

可以看出编译器提示不能实例化抽象类。

既然如此,抽象类的纯虚函数有什么作用呢?

抽象类实质上提供了不同种类的子类对象一个通用接口,用比较通俗的话来说就是基类声明,子类实现,因此子类如果需要创建对象,就必须实现基类中所有的纯虚函数,否则子类依然是一个抽象类,编译器同样会报错。

这个架构也使得新的应用程序可以很容易地被添加到系统中,即使是在系统被定义之后依然可以如此。

示例

#include <iostream>
using namespace std;

// 基类
class Shape{
    public:
    // 提供接口框架和纯虚函数
    virtual int getArea() = 0;
    void setWidth(int w) {
        width = w;
    }
    void setHeight(int h) {
        height = h;
    }

    protected:
    int width;
    int height;

};

// 派生类:矩形
class Rectangle: public Shape {
    public:
    int getArea() {
        return (width * height);
    }
};

// 派生类:三角形
class Triangle: public Shape {
    public:
    int getArea() {
        return (width * height)/2;
    }
};

int main(){
    Rectangle Rect;
    Triangle Tri;

    Rect.setWidth(10);
    Rect.setHeight(20);
    cout<< "矩形对象的面积为" <<Rect.getArea()<<endl;

    Tri.setWidth(10);
    Tri.setHeight(20);
    cout <<"三角形对象的面积为"<< Tri.getArea()<< endl;

    return 0;
}

调试结果为:

矩形对象的面积为200
三角形对象的面积为100
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值