1 类的继承与派生
三种继承方式:公有继承、私有继承、保护继承
公有继承:class A : public B {}
公有继承最为常见,要使用基类的私有成员一般通过接口访问。
例子:point.h文件里有一个Point类,作为基类
//Point.h
#ifndef _POINT_H /防止多次定义,宏全大写,命名无所谓,最好与文件名保持一致
#define _POINT_H
#include <iostream>
using namespace std;
class Point {
public:
void initPoint(float x = 0, float y = 0) {
/公共接口,此函数让外界输入的参数改变私有成员变量x和y。
this->x = x; / this->表示该类的成员,后面可以接成员变量或成员函数
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
rec.h文件里有一个Rec派生类,继承基类Point
//rec.h
#ifndef _REC_H
#define _REC_H
#include <iostream>
#include "Point.h"
using namespace std;
class Rec : public Point {
public:
void initRec(float x, float y, float w, float h) {
/公共接口,改变私有成员变量w,h
initPoint(x, y); / 访问基类的函数
this->w = w;
this->h = h;
}
float getW() const { return w; }
float getH() const { return h; }
private:
float w, h;
};
#endif // _POINT_H
主函数
// 主函数
#include <iostream>
#include <cmath>
using namespace std;
#include "rec.h"
int main() {
Rec rec;
rec.initRec(1, 1.2, 5, 10); /通过Rec类的接口传入四个数,改变了Point类和Rec类的私有成员
rec.move(3, 2);
cout << "矩形的中心,以及宽和高为:" << endl;
cout << rec.getX() << endl << rec.getY() << endl
<< rec.getW() << endl << rec.getH() << endl;
return 0;
}