7.1继承的基本概念和语法
继承:保持已有类的特性而构造新类的过程称为继承
派生:在已有类的基础上新增自己的特性而产生新类的过程称为派生。
继承与派生的目的:
继承的目的:实现设计与代码的重用。
派生的目的:当新的问题出现,原有程序无法解决(或不能完全解决)时,需要对原有程序进行改造。
派生类的构成:
1 吸收基类成员
2 改造基类成员
3 添加新的成员
默认情况下派生类包含了全部基类中除了构造和析构函数之外的所有成员。
c++11 规定可以用using语句继承基类构造函数
7.2 继承方式
1 继承方式简介及公有继承
不同继承方式的影响主要体现在:
派生类成员对基类成员的访问权限
通过派生类对象对基类成员的访问权限
三种继承方式:
公有继承
私有继承
保护继承
公有继承:
继承的访问控制:
基类的public和protected成员:访问属性在派生类中保持不变;
基类的private成员:不可直接访问。
访问权限:
派生类中的成员函数:可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员;
通过派生类的对象:只能访问public成员。
//7-1公有继承举例
//Point.h
#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
//Rectangle.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
//main.cpp
#include<iostream>
#include<cmath>
#include "Rectangle.h"
using namespace std;
int main(){
Rectangle rect; //定义Rectangle类的对象
//设置矩形的数据
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;
}
2 私有继承和保护继承
私有继承(private):
继承的访问控制
基类的public和protected成员:都以private身份出现在派生类中;
基类的private成员:不可直接访问。
访问权限
派生类中的成员函数:可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员;
通过派生类的对象:不能直接访问从基类继承的任何成员。
//Point.h
#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
//Rectangle.h
#ifndef _RECTANGLE_H
#define _RECTANGLE_H
#include "Point.h"
class Rectangle: private Point{
public: //新增公有函数成员
void initRectangle(float x, float y, float w, float h){
initPoint(x,y); //调用基类公有成员函数
this-> w = w;
this-> h = h;
}
void move(float offX, float offY){
Point::move(offX, offY);
}
float getX() const {return Point::getX();}
float getY() const {return Point::getY();}
float getH() const {return h;}
float getW() const {return w;}
private:
float w,h;
};
#endif //_RECTANGLE_H
//main.cpp
#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;
}
保护继承(protected)
继承的访问控制
基类的public和protected成员:都以protected身份出现在派生类中;
基类的private成员:不可直接访问。
访问权限
派生类中的成员函数:可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员;
通过派生类的对象:不能直接访问从基类继承的任何成员。