C++抽象类、虚函数、纯虚函数

C++ 接口是使用抽象类来实现的,抽象类与数据抽象互不混淆,数据抽象是一个把实现细节与相关的数据分离开的概念。

如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。纯虚函数是通过在声明中使用 “= 0” 来指定的

如 virtual int fun()=0;


定义一个函数为虚函数,不代表函数为不被实现的函数。

定义他为虚函数是为了允许用基类的指针来调用子类的这个函数。

定义一个函数为纯虚函数,才代表函数没有被实现。

定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序员必须实现这个函数。带纯虚函数的类叫虚基类,这种基类不能直接生成对象,而只有被继承,并重写其虚函数后,才能使用。


#include "stdafx.h"
#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 _tmain(int argc, _TCHAR* argv[])
{
Rectangle rec;
Triangle tri;
rec.setHeight(10);
rec.setWidth(10);

tri.setHeight(10);
tri.setWidth(10);

cout << "rectangle area:" << rec.getArea() << endl;
cout << "rectangle area:" << tri.getArea() << endl;



system("pause");
return 0;
}

rectangle area:100
rectangle area:50


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值