本文主要是介绍2018.6.7(多态性----几何形体处理程序----mooc),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
菜鸟教程
http://www.runoob.com/cplusplus/cpp-polymorphism.html
北大mooc
https://www.icourse163.org/learn/PKU-1002029030?tid=1002785058#/learn/content?type=detail&id=1003870405&cid=1004682705
派生类中和基类虚函数同名同参数的函数,不加virtual也自动成为虚函数
#include<iostream>
#include<cstdio>
#include<cmath>//sqrt头文件
#include<cstdlib>//qsort头文件
#include<algorithm>//sort头文件
using namespace std;class Shape
{
public:virtual double Area()=0;//纯虚函数virtual void Print()=0;//纯虚函数
};
class Rectangle:public Shape
{
public:double length,breadth;
public:virtual double Area();virtual void Print();
};
double Rectangle::Area()
{return length*breadth;
}
void Rectangle::Print()
{printf("Rectangle:%.2f\n",Area());
}class Triangle:public Shape
{
public:double a,b,c;
public:virtual double Area();virtual void Print();
};
double Triangle::Area()
{double p=(a+b+c)/2;return sqrt(p*(p-a)*(p-b)*(p-c));//海伦公式求三角形面积
}
void Triangle::Print()
{printf("Triangle:%.2f\n",Area());
}
class Circle:public Shape
{
public:#define PI 3.14double random;
public:virtual double Area();virtual void Print();
};
double Circle::Area()
{return PI*random*random;
}
void Circle::Print()
{printf("Circle:%.2f\n",Area());
}int compare(const void *s1,const void *s2)//自定义比较函数
{double a1;double a2;Shape **p1,**p2;p1=(Shape**)s1;p2=(Shape**)s2;a1=(*p1)->Area();a2=(*p2)->Area();if(a1<a2)return -1;else if(a1>a2)return 1;elsereturn 0;
}
bool cmp(Shape *a,Shape *b)
{return a->Area()<b->Area();
}//sort函数排序规则;int main()
{Shape *p_shape[100];Rectangle *p_r;Triangle *p_t;Circle *p_c;int n;cin>>n;for(int i=0;i<n;i++){getchar();char c;cin>>c;switch(c){case 'R':p_r=new Rectangle();cin>>p_r->length>>p_r->breadth;p_shape[i]=p_r;break;case 'T':p_t=new Triangle();cin>>p_t->a>>p_t->b>>p_t->c;p_shape[i]=p_t;break;case 'C':p_c=new Circle();cin>>p_c->random;p_shape[i]=p_c;break;}}cout<<"accomplish\n";qsort(p_shape,n,sizeof(Shape *),compare);//sort(p_shape,p_shape+n,cmp);for(int i=0;i<n;i++)p_shape[i]->Print();delete p_shape;return 0;
}
海伦公式求三角形面积
https://blog.csdn.net/chao1983210400/article/details/10521439
qsort函数用法
http://www.cnblogs.com/syxchina/archive/2010/07/29/2197382.html
这篇关于2018.6.7(多态性----几何形体处理程序----mooc)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!