定义一个 Rectangle 类,它包含两个数据成员 length 和 width;以及包含用于求长方形面积的成员函数。
再定义 Rectangle 的派生类 Rectangular,它包含一个新数据成员 height 和用来求长方体体积的成员函数。
在 main 函数中,使用两个类,求某个长方形的面积和某个长方体的体积。
定义一个 Rectangle 类,它包含两个数据成员 length 和 width;以及包含用于求长方形面积的成员函数。
再定义 Rectangle 的派生类 Rectangular,它包含一个新数据成员 height 和用来求长方体体积的成员函数。
在 main 函数中,使用两个类,求某个长方形的面积和某个长方体的体积。
#include<iostream>
using namespace std;
class Rectangle
{
private:
double Length;//长度
double Width;//宽度
public:
Rectangle(double length, double width)
{
//定义一个有两个参数的构造函数,用于设置长方形的宽度和长度
this->Length = length;
this->Width = width;
}
double Area() { //求面积函数
return Width * Length;//返回长度和宽度的乘积
}
};
class Rectangular :Rectangle
{
private:
double Height;
public:
Rectangular(double length, double width, double height) :Rectangle(length, width) {
// 定义一个有三个参数的构造函数,用于设置立方体的宽度和长度以及高度
this->Height = height;
}
double Volume() {//求体积函数
return this->Area() * Height;//返回长度和宽度及高度的乘积
}
};
int main()
{
Rectangle rect(3, 6);//定义长方体类实例
cout<<"面积:<<rect.Area()<<"<<endl;//调用求面积方法并输出结果
Rectangular rguar(5, 10, 3);//定义立方体类实例
cout<<"体积:<<rguar.Volume()<<"<<endl;//调用求体积方法并输出结果
system("pause")
return 0;
}
https://zhidao.baidu.com/question/136666505325430885.html