纯虚基类与虚函数的使用

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:30   1825   0

图形虚基类,定义计算面积跟周长的函数。派生出圆形,三角形,矩形子类,并重新定义基类计算面积与周长的函数。

注意:当基类的指针指向派生类的时候,只能操作派生类中从基类中继承过来的数据。

虚基类:

class graph  
{
public:
 virtual double perimeter() const= 0;
 virtual double area() const= 0; 
};

circle类:

#include"graph.h"

class circle:public graph 
{
public:
 circle(double r):radius(r){};//初始化成员列表
 virtual ~circle();
 double perimeter() const;
 double area() const;
private:
 double radius;
};

#include "circle.h"
#define PI 3.14159


double circle::area() const
{
 return this->radius*this->radius*PI;
}

double circle::perimeter() const
{
 return 2*this->radius*PI;
}


rectangle类:

#include"graph.h"

class rectangle:public graph
{
public:
 rectangle(double w,double h):width(w),height(h){};
 virtual ~rectangle();
 double perimeter() const;
 double area() const; 
private:
 double width;
 double height;

};


#include "rectangle.h"

double rectangle::area() const
{
 return this->height*this->width;
}

double rectangle::perimeter() const
{
 return 2*(this->height+this->width);
}


triangle类:

#include"graph.h"

class triangle:public graph
{
public:
 triangle(double a,double b,double c):boder1(a),boder2(b),boder3(c){};
 virtual ~triangle();
 double area() const;
 double perimeter() const;
private:
 double boder1;
 double boder2;
 double boder3;
};


#include "triangle.h"
#include<cmath>


double triangle::area() const
{
 double ave = (this->boder1+this->boder2+this->boder3)/2;
 return sqrtf(ave*(ave-this->boder1)*(ave-this->boder2)*(ave-this->boder3)); //利用海伦公式
}

double triangle::perimeter() const
{
 return this->boder1+this->boder2+this->boder3;
}


主函数:

#include<iostream>
#include<stdlib.h>
#include<vector>
#include<iterator>
#include"circle.h"
#include"graph.h"
#include"triangle.h"
#include"rectangle.h"

using namespace std;

int main()
{
 graph* c = new circle(22.3);
 graph* r = new rectangle(4.5,6.7);
 graph* t = new triangle(2.3,4.4,5.5);

 cout<<c->area()<<endl;
 cout<<r->area()<<endl;
 cout<<t->area()<<endl;
 
 vector<graph*> all;
 all.push_back(c);
 all.push_back(r);
 all.push_back(t);

 vector<graph*>::iterator ptr = all.begin();

 for(ptr;ptr != all.end();ptr++)
 {
  cout<<(*ptr)->area()<<endl;
  cout<<(*ptr)->perimeter()<<endl;
 }

 system("pause");
 return 0;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP