又来编程问题
发布网友
发布时间:2022-04-30 00:02
我来回答
共1个回答
热心网友
时间:2022-06-26 17:28
1.CArea不需要设为CShape的派生类。它也不需要得到CTriangle、CRect、CCircle这几个派生类的数据,只需要调用这几个派生类的Area函数来计算就可以了。
2.SetData的作用在题目中就已经说明了,它是用来重设图形大小的。
3.可以在CArea中调用各派生类的构造函数或成员函数来设置形状的数据。
#include
<iostream>
#include
<cmath>using
namespace
std;class
CShape
{
public:
virtual
double
Area()
=
0;
virtual
void
SetData()
=
0;
};class
CTriangle:public
CShape
{
double
a,
b,
c;
public:
CTriangle()
{
a
=
b
=
c
=
0.0;
}
CTriangle(double
A,
double
B,
double
C)
{
a
=
A;
b
=
B;
c
=
C;
}
virtual
double
Area()
{
double
p
=
(a
+
b
+
c)
/
2.0;
return
sqrt(p
*
(p
-
a)
*
(p
-
b)
*
(p
-
c));
}
virtual
void
SetData()
{
cout
<<
"输入三角形的三边长:\n";
cin
>>
a
>>
b
>>
c;
}
};class
CRect:public
CShape
{
double
h,
w;
public:
CRect()
{
h
=
w
=
0.0;
}
CRect(double
H,
double
W)
{
h
=
H;
w
=
W;
}
virtual
double
Area()
{
return
h
*
w;
}
virtual
void
SetData()
{
cout
<<
"输入矩形的长和宽:\n";
cin
>>
h
>>
w;
}
};class
CCircle:public
CShape
{
double
r;
public:
CCircle()
{
r
=
0.0;
}
CCircle(double
R)
{
r
=
R;
}
virtual
double
Area()
{
return
r
*
r
*
3.14;
}
virtual
void
SetData()
{
cout
<<
"输入圆形的半径:\n";
cin
>>
r;
}
};class
CArea
{
CShape
*s[3];
public:
CArea(double
TA
=
0.0,
double
TB
=
0.0,
double
TC
=
0.0,
double
RH
=
0.0,
double
RW
=
0.0,
double
CR
=
0.0)
{
s[0]
=
new
CTriangle(TA,
TB,
TC);
s[1]
=
new
CRect(RH,
RW);
s[2]
=
new
CCircle(CR);
}
~CArea()
{
delete
s[0];
delete
s[1];
delete
s[2];
}
void
SetData()
{
s[0]->SetData();
s[1]->SetData();
s[2]->SetData();
}
double
GetArea()
{
return
s[0]->Area()
+
s[1]->Area()
+
s[2]->Area();
}
};int
main()
{
CArea
area(3.0,
4.0,
5.0,
3.0,
5.0,
3.0);
cout
<<
"图形面积之和:"
<<
area.GetArea()
<<
endl;
area.SetData();
cout
<<
"图形面积之和:"
<<
area.GetArea()
<<
endl;
return
0;
}