【发布时间】:2021-04-13 03:36:07
【问题描述】:
创建一个名为 Rectangle 的类,具有长宽和面积。使用适当的成员函数从用户那里读取长度和宽度并计算矩形的面积。从类 rectangle 中创建一个名为 Box 的派生类。使用适当的成员函数来读取高度并计算体积。
#include <iostream>
using namespace std;
class Rectangle
{
protected:
int length;
int breadth;
int area;
public:
int input();
int calc();
};
int Rectangle::input()
{
cout<<"Enter the length and breadth:"<<endl;
cin>>length>>breadth;
return 0;
}
int Rectangle::calc()
{
area=length*breadth;
cout<<"Area: "<<area<<endl;
return 0;
}
class Box:public Rectangle
{
int height;
public:
int input();
int vol();
};
int Box::input()
{
cout<<"Enter the height:";
cin>>height;
return 0;
}
int Box::vol()
{
cout<<"Volume: "<<area*height<<endl;
return 0;
}
int main()
{
Rectangle r;
Box b;
r.input();
r.calc();
cout<<endl;
b.input();
b.vol();
return 0;
}
【问题讨论】:
-
可能是溢出。输入较小的数字,例如 20 和 50。
-
在 2 或 3 上都不起作用。在派生类中传递区域值时,传递的区域值为 -919949024。
-
Rectangle r;- 你不需要这个,Box b;已经包含一个Rectangle子对象。r.input(); r.calc();- 将其替换为b.Rectangle::input(); b.calc();。尽管重新考虑类的设计会更好,这样您就不必每次使用它们时都记住所有这些舞蹈。 -
读取未初始化的变量会让你的程序拥有undefined behavior。
标签: c++