源程序:
//直角三角形在派生矩形类,矩形类的参数也由键盘输入。设计这些类并测试他们的功能。
#include < iostream >
#include < cmath >
using namespace std;
class Line//线段基类
{
protected:
double sizeA;
public:
Line()
{
cout << "输入线段的长度:" << endl;
cin >> sizeA;
}
Line(double a)
{
sizeA = a;
}
double getLength()
{
return sizeA;
}
};
class Triangle : public Line//三角形类
{
protected:
double sizeB, sizeC;
public:
Triangle()
{
cout << "输入线段长度:" << endl;
cin >> sizeB;
sizeC = sqrt(sizeB * sizeB + sizeA * sizeA);
}
void printSize()
{
cout << "直角三角形,三条边分别为:";
cout << "A: " << sizeA << ", b: " << sizeB << ", C: " << sizeC << endl;
}
};
class Rectangle : public Triangle//矩形类
{
protected:
double sizeD;
public:
Rectangle()
{
sizeC = sizeA;
sizeD = sizeB;
}
void printSize()
{
cout << "矩形,四条边分别为:";
cout << "A: " << sizeA << ", b: " << sizeB << ", C: " << sizeC << ", D: " << sizeD << endl;
}
};
void main()
{
Line *l = new Line();
cout << "线段长度为:" << l->getLength() << endl;
Triangle *t = new Triangle();
t->printSize();
Rectangle *r = new Rectangle();
r->printSize();
system("pause");
}
运行结果: