c++程序设计问题
发布网友
发布时间:2023-09-03 22:51
我来回答
共2个回答
热心网友
时间:2024-12-04 12:52
#include<iostream>
using namespace std;
class Shape
{
public:
virtual float area() const =0;
virtual void shapeName() const =0;
};
class Triangle:public Shape
{
public:
Triangle(float e1=0,float e2=0,float e3=0):edge1(e1),edge2(e2),edge3(e3){}
bool isTriangle() const
{
if(((edge1+edge2)>edge3)&&((edge1+edge3)>edge2)&&((edge3+edge2)>edge1))
return true;
else
return false;
}
void shapeName() const
{
cout<<"Triangle:";
cout<<"edge1="<<edge1<<",edge2="<<edge2<<",edge3="<<edge3;
cout<<endl;
}
float area() const
{
float temp=(edge1+edge2+edge3)/2;
if(isTriangle())
return sqrt(temp*(temp-edge1)*(temp-edge2)*(temp-edge3));
else
{
cout<<"Not a Triangle!"<<endl;
return -1;
}
}
private:
float edge1,edge2,edge3;
};
class Square:public Shape
{
public:
Square(float e=0):edge(e){}
float area() const
{
return edge*edge;
}
void shapeName() const
{
cout<<"Square:";
cout<<"edge="<<edge;
cout<<endl;
}
private:
float edge;
};
class Circle:public Shape
{
public:
Circle(float r):radius(r){}
float area() const
{
return 2*3.14*radius*radius;
}
void shapeName() const
{
cout<<"Circle:";
cout<<"radius="<<radius;
cout<<endl;
}
private:
float radius;
};
int main()
{
Triangle t(3,4,5);
Square s(5);
Circle c(3);
Shape * shape;
shape=&t;
shape->shapeName();
cout<<"area="<<shape->area();
cout<<endl;
shape=&s;
shape->shapeName();
cout<<"area="<<shape->area();
cout<<endl;
shape=&c;
shape->shapeName();
cout<<"area="<<shape->area();
cout<<endl;
return 0;
}
热心网友
时间:2024-12-04 12:53
#include <iostream>
#include <math.h>
using namespace std;
#definePIE3.14
//图形类
class CShape
{
public:
virtual void CalcArea()=NULL;
};
//三角形类
class Triangle : public CShape
{
long double m_dSidelength;//边长
long double m_dHighlength;//对边的高
public:
Triangle()
{
m_dSidelength = 0;
m_dHighlength = 0;
}
Triangle(long double dSidelength,long double dHighlength)
{
m_dSidelength = dSidelength;
m_dHighlength = dHighlength;
}
~Triangle();
virtual void CalcArea()
{
cout<<"三角形类面积:"<<m_dSidelength*m_dHighlength/2<<endl;
}
};
//正方形类
class Square : public CShape
{
protected:
long double m_dSidelength;//边长
public:
Square(){m_dSidelength = 0;}
Square(long double dSidelength){ m_dSidelength = dSidelength;}
~Square();
virtual void CalcArea()
{
cout<<"正方形类面积:"<<pow(m_dSidelength,2)<<endl;
}
};
//圆形类
class Circle : public CShape
{
protected:
long double m_dRadius;//半径
public:
Circle(){m_dRadius = 0;}
Circle(long double dRadius){ m_dRadius = dRadius;}
~Circle(){}
virtual void CalcArea()
{
cout<<"圆形类面积:"<<PIE*pow(m_dRadius,2)<<endl;
}
};
void main()
{
CShape *m_pCircle = new Circle(10);
CShape *m_pSquare = new Square(10);
CShape *m_pTriangle = new Triangle(10,10);
m_pCircle->CalcArea();
m_pSquare->CalcArea();
m_pTriangle->CalcArea();
delete m_pCircle;
delete m_pSquare;
delete m_pTriangle;
getchar();
}