首页 技术 正文
技术 2022年11月16日
0 收藏 331 点赞 4,339 浏览 1656 个字

继承与派生

基本概念和语法

概念

  • 继承与派生是同一过程从不同角度看

    保持已有的特性而构造新类的过程称为继承。

    在已有类的基础上新增自己的特性而产生新类的过程为派生。

  • 被继承的已有类称为基类(父类)
  • 派生出的新类称为派生类(或子类)
  • 直接参与派生出某类的基类称为直接基类。
  • 基类的基类甚至更高的基类称为间接基类。

定义

语法:

单继承:

class 派生类名:继承方式 基类名{

成员声明;

}

多继承:

class 派生类名:继承方式1 基类名,继承方式2 基类名2,…

{

成员声明;

}

派生类的构成

  • 吸收基类成员
  • 改造基类的成员
  • 添加新的成员

吸收:吸收基类成员:包含了全部基类中除构造和析构函数之外的所以成员,但可以用using语句继承基类构造函数

改造:若派生类中有和基类中同名的函数时,基类的会被覆盖

添加:添加新功能和数据

继承方式

不同继承方式的影响体现在:

  • 派生类成员对基类成员的访问权限
  • 通过派生类对象对基类成员的访问权限

举例:


using namespace std;class Point{
public:
void initP(float xx,float yy)
{
x=xx;
y=yy;
}
void Move(float xOff,float yOff){
x+=xOff;
y+=yOff;
}
float GetX()const{return x;}
float GetY()const{return y;}
private:
float x,y;};
class Rectangle:public Point{
public:
void initRectangle(float x,float y,float w,float h){
initP(x,y);
this->w=w;
this->h=h;
}
float GetH(){return h;}
float GetW(){return w;}
private:
float w,h;
};
int main(){
Rectangle a;
a.initRectangle(1,2,3,4);
a.Move(1,2);
cout<<a.GetX()<<endl;
cout<<a.GetY()<<endl;
cout<<a.GetW()<<endl;
cout<<a.GetH()<<endl;
return 0;
}

可以看出,声明的rectangle对象可以调用父类Point的成员

私有继承和保护继承

  • 私有继承:

    私有继承,继承过来的父类的public只能在类内调用,但是不能被对象直接调用,私有继承的父类的公有成员为派生类的私有成员

由图中可见,只能在类中调用私有继承,不能直接调用。

  • 保护继承

对建立其所在类对象的模块来说,它与private成员的性质相同。

对于其派生来说,它与父类public成员的性质相同。

其中的x相当于A类中的私有成员

作为B的父类时,又相当于A类中的公有成员

既实现了数据的隐藏,又方便继承,实现代码重用。

最后举个多继承的例子:

#include<iostream>
using namespace std;
class A{
public:
void setA(int aa){
a = aa;
}
void showA()const{
cout<<a<<endl;
}
private:
int a;
};
class B{
public:
void setB(int bb){
b = bb;
}
void showB()const{
cout<<b<<endl;
}
private:
int b;
};
class C:public A,private B{
public:
void setC(int a,int b,int c){
setA(a);
setB(b);
this->c = c;
}
showC()const{
cout<<c<<endl;
}
private:
int c;
};
int main(){
C test;
test.setA(5);
test.showA();
test.setC(6,7,9);
test.showC();
test.setB(6);
}

可以看到,test.setA和setC是可以调用的,public成员可以直接在对象上调用,而私有成员只能在类内的成员中调用,不能被对象直接调用。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,996
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,510
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,353
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,137
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848