C++纯虚函数与抽象类
来源:互联网 发布:java连接符 编辑:程序博客网 时间:2024/05/17 04:44
在很多的情况下,在基类中一般都不能给出虚函数的具体而有意义的定义,这时我们就可以将它说明为纯虚函数。它的具体的定义由它的派生类具体完成,这样可以使类之间的结构更加清晰,同时也更容易理解。
含有纯虚函数的类叫抽象类。
说明纯虚函数的一般格式:
class 类名
{
virtual 返回值类型 函数名(参数列表)=0;
}
#ifndef _______Shape__
#define _______Shape__
#include <iostream>
class Shape
{
private:
int x;
int y;
public:
void setX(int _x,int _y);
int getX();
int getY();
virtual float area()=0;//纯虚函数。
};
#endif /* defined(_______Shape__) */
#include "Shape.h"
voidShape::setX(int _x,int _y)
{
x=_x;
y=_y;
}
intShape::getX()
{
return x;
}
intShape::getY()
{
return y;
}
#ifndef _______Rectangle__
#define _______Rectangle__
#include <iostream>
#include "Shape.h"
class Rectangle :publicShape
{
private:
int width;
int height;
public:
void setWH(int _w,int _h);
int getWidth();
int getHeigth();
float area();
};
#endif /* defined(_______Rectangle__) */
#include "Rectangle.h"
voidRectangle::setWH(int _w,int _h)
{
width=_w;
height=_h;
}
intRectangle:: getWidth()
{
return width;
}
intRectangle::getHeigth()
{
return height;
}
floatRectangle:: area()
{
returnwidth*height;
}
#include <iostream>
#include "Rectangle.h"
#include "Shape.h"
using namespacestd;
int main(int argc,const char * argv[])
{
Shape *p;
Rectangle rect;
rect.setWH(10,20);
p=▭//加上virtual,基类可以调用派生类的函数。
cout<<p->area()<<endl;//调用派生类的函数,实现多态5
return 0;
}
- C++:纯虚函数与抽象类
- 【c++】纯虚函数和抽象类
- [C++]纯虚函数和抽象类
- 纯虚函数与抽象类
- 纯虚函数与抽象类
- 抽象类与纯虚函数
- C++纯虚函数与抽象类
- 纯虚函数与抽象类练习题
- C++纯虚函数与抽象类
- C++纯虚函数与抽象类
- 纯虚函数与抽象类
- C++抽象类与纯虚函数
- 抽象类与纯虚函数
- 纯虚函数与抽象类
- C++ 抽象类与纯虚函数
- C++ 纯虚函数与抽象类
- 纯虚函数与抽象基类
- C++纯虚函数与抽象类
- 高中必修的指数函数代码
- 事务日志满场景/回溯
- java访问修饰符详解
- Intent如何传递对象
- xe4 StringReplace
- C++纯虚函数与抽象类
- oracle常用命令
- 面试题2
- vs2010 类模板 friend 函数无法调用类的private 模板类,模板函数
- Linux的crontab安装和详解
- 垃圾回收 学习笔记(一)
- Stringsobits
- 对android应用进行代码混淆
- TOMCAT源码分析 http消息解析