继承
理解继承的概念
在C++中,“继承”是指在已存在的类的基础上建立一个新类。已存在的类称为“基类”或者“父类”,新建立的类称为“子类”或者“派生类”。
在建立派生类的过程中,基类没有任何变化。派生类除了继承基类的所有可引用的成员变量和成员函数外,还可以定义本身的成员变量和函数。
有三种派生方式:共有(public)、保护(protected)、私有(private)
格式:class ClassName:<Access>BaseClassName{....}
公有派生:
基类中所有成员在派生类中保持不变。
public:在派生类和类外可以使用。
protected:在派生类中使用。
private:不能在派生类中使用。
私有派生:
基类:public:(变为私有)在派生类可以使用,类外不可以使用。
protected:(变为私有)在派生类可以使用,类外不可以使用。
private:不能在派生类和类外中使用。
保护派生:
基类:public:(变为保护)在派生类可以使用,类外不可以使用。
protected:(变为私有)在派生类可以使用,类外不可以使用。
private:不能在派生类和类外中使用。
抽象类:
将类的构造函数或者析构函数设置为保护时,这种类为抽象类。
单继承
#include <iostream>
using namespace std;
class A
{
private:
int x;
protected:
int y;
public:
int z;
A(int a, int b, int c)
{
cout << "基类" << endl;
x = a;
y = b;
z = c;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
int getz()
{
return z;
}
void dispA()
{
cout << "x=" << x << " y=" << y << " z=" << z << endl;
}
};
class B:public A
{
private:
int m;
int n;
public:
B(int a, int b, int c, int d,int e) :A(a, b, c)
{
cout << "子类" << endl;
m = d;
n = e;
}
void dispB()
{
cout << "x=" << getx() << " y=" << y << " z=" << z << endl;
}
void sum()
{
cout << "sum=" << getx() + y + z + m + n << endl;
}
};
int main()
{
B obj(1, 2, 3, 4, 5);
obj.dispA();
obj.dispB();
obj.sum();
}
多继承
格式:class D:public A,protected B,private C{...}