类继承是在现有类的基础上创造新类的机制。
称现有的类为基类(父类),建立的类为派生类(子类)。
如果两个类的实现有某些显著的共同点,则将这些共同点做成一个基类。
若派生类有一个直接基类,记作单继承;反之记作多继承。
继承方式:public, private, protected.
不同继承方式的影响方式主要是:
- 派生类成员对基类成员的访问控制
- 派生类对象对基类成员的访问控制
下面举一个例子:
//下面我们以画图形为例,下列文本在Tshape.h中
class TShape{ //基类
private:
int color;
int x;
int y;
public:
TShape(); //构造函数
int getx();
int gety();
void setx(int nx);
void sety(int ny);
void draw();
};
//下列的代码在Tshape.cpp中
#include "TShape.h"
#include
TShape::TShape(){ //构造函数,默认初始化图像的中心点为(10, 10)
x = 10;
y = 10;
}
std::void TShape::Draw(){
std::cout<<"画了吗?如画"<< std::endl;
}
在上面,我们成功写出了一个最基础的基类shape,随后,我们可以在shape下面继续构造circle, triangle等等子类。子类继承shape的color,x, y等成员,但同时具有自己独有的成员和方法。
//TEllipse.h(T椭圆.h)
#include "TShape.h"
class TEllipse: public Tshape{ //单冒号表示继承关系,双冒号表示作用域运算符
//继承后,没有写的父类会全部被复制过来
public:
void Draw(); //父类里面已经有了,这个Draw会被替换掉.
void seta(int na);
void setb(int nb);
private:
int a;
int b;
}
//TEllipse.cpp
#include "TEllipse.h"
#include
void TEllipse::Draw(){
std::cout<<"这是椭圆,但画了吗?如画"<
using namespace std;
int main(){
TEllipse myEllipse;
cout << "x = " << myEllipse.getx() << endl;
cout << "y = " << myEllipse.gety() << endl; // getx和gety被继承。
TEllipse::Draw();
return 0;
}