您的位置:首页 > 编程语言 > C语言/C++

从零学习C++第七篇:继承和派生

2018-03-09 17:33 344 查看
一、继承和派生
派生:通过已有的类(基类)建立新类(派生类)的过程,叫做派生。
继承:派生类继承基类的数据成员和函数。分为单一继承和多重继承。
单一继承
class  派生类名  : 访问控制符  基类名{    //访问控制符是控制派生类成员访问基类成员  public:公有派生、private:私有派生、protected:保护派生。

}
构造函数:派生类名::派生类名(参数列表):基类名(参数列表){
//函数体
}/*从基类Point派生出一个描述矩形的类Rectangle*/
#include <iostream>
using namespace std;
class Point{
//protected: //控制访问protected 对于派生类来说 是共有的 对于其它类 不可访问
// float x,y;//描述矩形一个顶点的坐标
private:
float x,y;
public:
Point(int a,int b):x(a),y(b){}
void showxy(){
cout<<"x:"<<x<<" y:"<<y<<endl;
}
};
class Rectangle : public Point{
private:
float H,W;//描述矩形的高和宽
public:
Rectangle(float a,float b,float c,float d):Point(a,b){
H=c;
W=d;
}
// void show(){
// cout<<"x:"<<x<<" y:"<<y<<" H:"<<H<<" W:"<<W;
// }
void show(){
cout<<" H:"<<H<<" W:"<<W;
}//当基类数据控制访问为private 不能直接访问

};
int main() {
Rectangle A(3.2,4.5,6.2,9.8);
A.showxy();
A.show();//当派生类与基类函数同名时,默认调用派生类
return 0;
}运行结果:x:3 y:4
H:6.2 W:9.8isa(就是一个)和has-a(有一个)的区别
多重继承
一个函数继承多个函数
class 类名 :控制访问符 类1,控制访问符 类2,...控制访问符 类n#include <iostream>
using namespace std;
class A{
protected:
int x;
public:
A(int a){
x=a;
}

int getX() const {
return x;
}
void showA(){
cout<<"x:"<<x<<endl;
}

void setX(int x) {
this->x = x;
}
};
class B{
protected:
int y;
public:
B(int a){
y=a;
}

int getY() const {
return y;
}
void showB(){
cout<<y<<endl;
}

void setY(int y) {
this->y = y;
}
};
class C{
protected:
int z;
public:
C(int a){
z=a;
}

int getZ() const {
return z;
}
void showC(){
cout<<z<<endl;
}

void setZ(int z) {
this->z = z;
}
};
class S:public A,private B,protected C{//公有派生、私有派生、保护派生。
protected:
int r;
public:
S();
S (int a,int b,int c,int d):A(a),B(b),C(c){
r=d;
}
void show(){
cout<<"x:"<<x<<" y:"<<y<<" z:"<<z<<" r:"<<r<<endl;
}

int getR() const {
return r;
}
};
int main() {
S a(3,6,9,12);
a.show();
a.setX(10);
a.showA();
a.show();

// a.setY(10);
// a.showB(); //私有派生 不能调用set()直接设置X值 只能维护和显示

// a.setZ(10);
// a.showC(); //保护派生 使原来的权限都降了一级 public→protected protected→private private变成不可访问
return 0;
}运行结果:x:3 y:6 z:9 r:12
x:10
x:10 y:6 z:9 r:12二、二义性及其支配规则
一个表达式可以解释为访问多个基类中的成员,则称这种访问具有二义性。
可以使用作用域分辨运算符“::”和成员名限定解决二义性。#include <iostream>
using namespace std;
class A{
public:
void func(){
cout<<"A.func()"<<endl;
}
};
class B{
public:
void func(){
cout<<"B.func()"<<endl;
}
};
class C{
public:
void func(){
cout<<"C.func()"<<endl;
}
};
class D:public A,protected B,private C{
public:
void gunc(){
cout<<"D.gunc"<<endl;
}
void hunc(){
// func();//具有二义性 不知道执行哪个类的func()方法
A::func();//用作用域分辨运算符解决 类名::标识符

}

};
int main() {
D a;
a.hunc();
// a.func();//具有二义性
a.A::func();
return 0;
}当派生类和基类有同名函数时,对象先调用自己的同名成员函数,可以用作用域运算符指定调用哪个方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: