问题描述
- 急求,c++形状类的周长和面积 用虚函数写
-
//1.定义形状类Shape,使其包含两个私有数据成员:float perimeter; float area;
//2.定义三角形类Triangle,从Shape继承,并包含三个私有数据成员:float edge1; float edge2; float edge3;定义两个共有成员函数:float CalcPeri(); float CalcArea();
//3.定义矩形类Rectangle,从Shape继承,并包含两个私有数据成员:float width; float height; 定义两个共有成员函数:float CalcPeri(); float CalcArea();
//4.设计一个全局函数:float AddShape(Shape *s[ ], int n)用于实现n个指定形状(可以是三角形、矩形或兼而有之)的面积之和。
//5.在main函数中对上述设计进行测试。#include
#include
using namespace std;
//定义形状类
class Shape{
public:
Shape(float p=0,float a=0)
{
perimeter=p;
area=a;
}
virtual float area()=0;
virtual float perimeter()=0;
void sDisplay()
{
cout<<"周长是:"<
cout
}
pravite:
float perimeter;
float area;
};
//定义三角形类
class Triangle:public Shape{
public:
Triangle(float a,float b,float c)
{
edge1=a;
edge2=b;
edge3=c;
}
void tDisplay(){
cout
}
float CalcPeri(){
float p;
return p=edge1+edge2+edge3;
}
float CalcArea(){
float m=(edge1+edge2+edge3)/2;
return sqrt(m*(m-edge1)*(m-edge2)*(m-edge3));
}
private:
float edge1;
float edge2;
float edge3;
};
//定义长方形类
class Rectangle:public Shape{
public:
Rectangle(float width,float height)
{
width=w;
height=h;
}
void rDisplay()
{
cout
}
float CalcPeri()
{
return (width+height)*2;
}
float CalcArea()
{
return width*height;
}
private:
float width;
float height;
};
//定义多边形
float AddShape(Shape *s[],int n)
{
int p,q;
for(int i=0;i
{
p=s[i]->perimeter()+p;
q=s[i]->area()+q;
}
cout<<"多边形的周长是:"<cout
return 0;
}
int main()
{Triangle tri1(4,5,6);
Triangle tri2(3,4,5);
Rectangle rect(8,9);
Shape *s[]={&tri1,&tri2,rect};
for (int i=0;i
{coutarea()<
coutperimeter()<<endl;
}}
解决方案
http://blog.chinaunix.net/uid-20465760-id-1944082.html
关于虚函数的介绍,还有你到底要问什么?
解决方案二:
我想问我该怎么改,不太明白
解决方案三:
http://blog.chinaunix.net/uid-20465760-id-1944082.html
关于虚函数的介绍,还有你到底要问什么?