6.7C++ :类的继承与派生:公有继承

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;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值