5-1 继承与派生
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
通过本题目的练习可以掌握继承与派生的概念,派生类的定义和使用方法,其中派生类构造函数的定义是重点。
要求定义一个基类Point,它有两个私有的float型数据成员X,Y;一个构造函数用于对数据成员初始化;有一个成员函数void Move(float xOff, float yOff)实现分别对X,Y值的改变,其中参数xOff和yOff分别代表偏移量。另外两个成员函数GetX() 、GetY()分别返回X和Y的值。
Rectangle类是基类Point的公有派生类。它增加了两个float型的私有数据成员W,H; 增加了两个成员函数float GetH() 、float GetW()分别返回W和H的值;并定义了自己的构造函数,实现对各个数据成员的初始化。
编写主函数main()根据以下的输入输出提示,完成整个程序。
Input
6个float型的数据,分别代表矩形的横坐标X、纵坐标Y、宽度W,高度H、横向偏移量的值、纵向偏移量的值;每个数据之间用一个空格间隔
Output
输出数据共有4个,每个数据之间用一个空格间隔。分别代表偏移以后的矩形的横坐标X、纵坐标Y、宽度W,高度H的值
Example Input
5 6 2 3 1 2
Example Output
6 8 2 3
Hint
输入 -5 -6 -2 -3 2 10
输出 -3 4 0 0
Author
黄晶晶
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class point
{
private:float x,y;
public:
point(float a = 0,float b = 0)
{
x = a;
y = b;
}
void Move(float xoff,float yoff)
{
x = x + xoff;
y = y + yoff;
}
float getx()
{
return x;
}
float gety()
{
return y;
}
};
class Rectangle : public point
{
private:float w,h;
public:
Rectangle(float a = 0,float b = 0,float x = 0,float y = 0):point(x,y)//构造函数,初始化数据;
{
w = a;
h = b;
}
float getw()
{
return w;
}
float geth()
{
return h;
}
};
int main()
{
float x,y,w,h,xoff,yoff;
cin>>x>>y>>w>>h>>xoff>>yoff;
if(w < 0)w =0;
if(h < 0)h =0;
Rectangle a(w,h,x,y);
a.Move(xoff,yoff);//公有继承,可以直接使用基类公有成员函数;
cout<<a.getx()<<" "<<a.gety()<<" "<<a.getw()<<" "<<a.geth()<<endl;
return 0;
}