c++编程题.doc
文本预览下载声明
4.1测试一个名为rectangle的矩形类,其属性为矩形的左下角与右上角两个点的坐标,能计算矩形的面积。
解:
源程序:
#include iostream.h
class Rectangle
{
public:
Rectangle (int top, int left, int bottom, int right);
~Rectangle () {}
int GetTop() const { return itsTop; }
int GetLeft() const { return itsLeft; }
int GetBottom() const { return itsBottom; }
int GetRight() const { return itsRight; }
void SetTop(int top) { itsTop = top; }
void SetLeft (int left) { itsLeft = left; }
void SetBottom (int bottom) { itsBottom = bottom; }
void SetRight (int right) { itsRight = right; }
int GetArea() const;
private:
int itsTop;
int itsLeft;
int itsBottom;
int itsRight;
};
Rectangle::Rectangle(int top, int left, int bottom, int right)
{
itsTop = top;
itsLeft = left;
itsBottom = bottom;
itsRight = right;
}
int Rectangle::GetArea() const
{
int Width = itsRight-itsLeft;
int Height = itsTop - itsBottom;
return (Width * Height);
}
int main()
{
Rectangle MyRectangle (100, 20, 50, 80 );
int Area = MyRectangle.GetArea();
cout Area: Area \n;
return 0;
}
程序运行输出:
Area: 3000
Upper Left X Coordinate: 20
4.2设计一个程序。 设计一个立方体类Box,它能计算并输出立方体的体积和表面积。
#include?iostream
using?namespace?std;???
class?Box?
?{public:?
?float?L;?
float?getBMJ(){return?L*L*6;}
??float?getTJ(){return?L*L;}?
?Box(float?in){L=in;}?
?};???
?void?main()?
?{??
??Box?r(10);?
??cout边长:10\n表面积:r.getBMJ()\n体积:r.getTJ();?
?}
4.3设计一个汽车类vehicle,包含的数据成员有车轮个数wheels和车重weight。小车类car是它的派生类其中包含载人数passenger_load。每个类都有相关数据的输出方法。
class vehicle??//汽车类,包含车轮数和车重{?public:??vehicle(int, float);??int get_wheels();??float get_weight();??void show();?protected:??int wheels;????//车轮数??float weight;???//车重量,单位吨};
class car:private vehicle??//小车类是汽车类的私有派生类,包含载客数{?public:??car(int wheels, float weight, int passengers);??int get_passengers();??void show();?private:??int passenger_load;??//额定载客数};
class truck:private vehicle??//卡车类是汽车类的私有派生类,包含载人数和载重量{?public:??truck(int wheels,float weight,int passengers,float max_load);??int get_passengers();??void show();?private:??int passenger
显示全部