# C++第四次作业——继承

## Part 1 知识点

1）基本知识点

class 派生类名：继承方式 基类名1,继承方式 基类名2,继承方式 基类名3,……,继承方式 基类名n
{
派生类成员声明;
};


2）重要知识点

## Part 2 实验

#ifndef Point_h
#define Point_h
class Point {
public:
void initPoint (float x=0,float y=0){this->x =x ;this->y=y;}
void move(float offX,float offY) {x+=offX; y+=offY;}
float getX() const{return x;}
float getY() const{return y;}
private:
float x,y;
};
#endif /* Point_h */

#ifndef Rectangle_h
#define Rectangle_h
#include "Point.h"
class Rectangle:public Point {
public:
void initRectangle(float x,float y,float w,float h){
initPoint(x,y);
this->w=w;
this->h=h;
}
float getH()const {return h;}
float getW()const {return w;}
private:
float w,h;
};
#endif /* Rectangle_h */

#include <iostream>
#include <cmath>
#include "Rectangle.h"
using namespace std;
int main(){
Rectangle rect;
rect.initRectangle(2, 3, 20, 10);
rect.move(3, 2);
cout<<"The data of rect(x,y,w,h): "<<endl;
cout<<rect.getX()<<","
<<rect.getY()<<","
<<rect.getW()<<","
<<rect.getH()<<","<<endl;
return 0;
}



#ifndef Point_h
#define Point_h
class Point {
public:
void initPoint (float x=0,float y=0){this->x =x ;this->y=y;}
void move(float offX,float offY) {x+=offX; y+=offY;}
float getX() const{return x;}
float getY() const{return y;}
private:
float x,y;
};
#endif /* Point_h */

#ifndef Rectangle_h
#define Rectangle_h
#include "Point.h"
class Rectangle:protected Point {					//这里用private来控制继承方式结果完全相同
public:
void initRectangle(float x,float y,float w,float h){
initPoint(x,y);
this->w=w;
this->h=h;
}
float getH()const {return h;}
float getW()const {return w;}
//下面是新增代码
void move(float offX,float offY){Point::move(offX,offY);}
float getX() const {return Point::getX();}
float getY() const {return Point::getY();}
private:
float w,h;
};
#endif /* Rectangle_h */

#include <iostream>
#include <cmath>
#include "Rectangle.h"
using namespace std;
int main(){
Rectangle rect;
rect.initRectangle(2, 3, 20, 10);
rect.move(3, 2);
cout<<"The data of rect(x,y,w,h): "<<endl;
cout<<rect.getX()<<","
<<rect.getY()<<","
<<rect.getW()<<","
<<rect.getH()<<","<<endl;
return 0;
}



#ifndef square_h
#define square_h
#include "Rectangle.h"
class square:private Rectangle {
public:
void initsquare(float x,float y,float w,float h){
initPoint(x,y);
this->w=w;
this->h=h;
}
float getH()const {return h;}
float getW()const {return w;}
void move(float offX,float offY){Point::move(offX,offY);}
float getX() const {return Point::getX();}
float getY() const {return Point::getY();}
private:
int j,k;
}
#endif /* square_h */



## Part 3 总结

posted @ 2019-10-13 23:30  rain-coding  阅读(179)  评论(0编辑  收藏  举报