版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hold_on_/article/details/78899225
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>
using namespace std;
using namespace std;
class point
{
private:
float x, y;
public:
point(){x = 0; y = 0;}//构造函数初始化
void move(float xOff, float yOff)
{
x = x + xOff;
y = y + yOff;
}
void get_point()
{
cin>>x>>y;
}
float getx(float xOff)
{
return x + xOff;
}
float gety(float yOff)
{
return y + yOff;
}
void show_point()
{
cout<<x<<" "<<y<<" ";
}
};
class rectangle:public point //派生类函数通俗的说就是基于基类的一个类
{
private:
float w, h;
public:
rectangle()//初始化
{
w = 0;
h = 0;
}
void get_rectangle()
{
get_point(); //调用基类的输入函数
cin>>w>>h;
if(w <= 0) w = 0; //越界置零
if(h <= 0) h = 0;
}
float getw()
{
return w;
}
float geth()
{
return h;
}
void show()
{
show_point(); //调用基类的输出函数
cout<<w<<" "<<h;
}
};
int main()
{
float n, m;
rectangle b;
b.get_rectangle();//这里要注意输入顺序
cin>>n>>m;
b.move(n, m);
b.show();
return 0;
}
//要调用就都调用,不能调用一个另一个不调用
{
private:
float x, y;
public:
point(){x = 0; y = 0;}//构造函数初始化
void move(float xOff, float yOff)
{
x = x + xOff;
y = y + yOff;
}
void get_point()
{
cin>>x>>y;
}
float getx(float xOff)
{
return x + xOff;
}
float gety(float yOff)
{
return y + yOff;
}
void show_point()
{
cout<<x<<" "<<y<<" ";
}
};
class rectangle:public point //派生类函数通俗的说就是基于基类的一个类
{
private:
float w, h;
public:
rectangle()//初始化
{
w = 0;
h = 0;
}
void get_rectangle()
{
get_point(); //调用基类的输入函数
cin>>w>>h;
if(w <= 0) w = 0; //越界置零
if(h <= 0) h = 0;
}
float getw()
{
return w;
}
float geth()
{
return h;
}
void show()
{
show_point(); //调用基类的输出函数
cout<<w<<" "<<h;
}
};
int main()
{
float n, m;
rectangle b;
b.get_rectangle();//这里要注意输入顺序
cin>>n>>m;
b.move(n, m);
b.show();
return 0;
}
//要调用就都调用,不能调用一个另一个不调用