分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
【题目】写一个程序,定义抽象基类Shape,由它派生出3个派生类,Circle(圆形)、Rectangle(矩形)、Triangle(三角形)。用如下的mian()函数,求出定义的几个几何体的面积和。
int main(){ Circle c1(12.6),c2(4.9); //建立Circle类对象c1,c2,参数为圆半径 Rectangle r1(4.5,8.4),r2(5.0,2.5); //建立Rectangle类对象r1,r2,参数为矩形长、宽 Triangle t1(4.5,8.4),t2(3.4,2.8); //建立Triangle类对象t1,t2,参数为三角形底边长与高 Shape *pt[6]={&c1,&c2,&r1,&r2,&t1,&t2}; //定义基类指针数组pt,各元素指向一个派生类对象 double areas=0.0; //areas为总面积 for(int i=0; i<6; i++) { areas=areas+pt[i]->area(); } cout<<"totol of all areas="<<areas<<endl; //输出总面积 system("pause"); return 0;}
【一点说明】
从main()函数中可以看出,要用指向Shape的指针pt[i]调用各种形状对应的area()函数,而各种形状求面积的方法当然不同。在这种情况下,在Shape中,将area()处理为虚函数是自然的事了。而确定Shape只用作基类,而不实例化后,将其处理成抽象类,是一种良好设计的考虑。
【参考解答】
#include <iostream>using namespace std;//定义抽象基类Shapeclass Shape{public: virtual double area() const =0; //纯虚函数};//定义Circle类class Circle:public Shape{public: Circle(double r):radius(r){} //结构函数 virtual double area() const {return 3.14159*radius*radius;}; //定义虚函数protected: double radius; //半径};//定义Rectangle类class Rectangle:public Shape{public: Rectangle(double w,double h):width(w),height(h){} //结构函数 virtual double area() const {return width*height;} //定义虚函数protected: double width,height; //宽与高};class Triangle:public Shape{public: Triangle(double w,double h):width(w),height(h){} //结构函数 virtual double area() const {return 0.5*width*height;} //定义虚函数protected: double width,height; //宽与高};int main(){ Circle c1(12.6),c2(4.9); //建立Circle类对象c1,c2,参数为圆半径 Rectangle r1(4.5,8.4),r2(5.0,2.5); //建立Rectangle类对象r1,r2,参数为矩形长、宽 Triangle t1(4.5,8.4),t2(3.4,2.8); //建立Triangle类对象t1,t2,参数为三角形底边长与高 Shape *pt[6]={&c1,&c2,&r1,&r2,&t1,&t2}; //定义基类指针数组pt,使它每一个元素指向一个派生类对象 double areas=0.0; //areas为总面积 for(int i=0;i<6;i++) { areas=areas+pt[i]->area(); } cout<<"totol of all areas="<<areas<<endl; //输出总面积 system("pause"); return 0;}
扫描二维码关注公众号,回复:
4104522 查看本文章