一、定义
类的继承:是从新的类从已有类那里得到已有的特性。
二、方式
1.公有继承:当类的继承方式为公有继承时,基类的公有成员和保护成员的访问属性在派生类中不变,而基类的私有成员不可直接访问。
例:
#include<iostream>
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() {return x;}
float getY() {return y;}
private:
float x,y;
};
class Rectangle:public Point //公有继承
{
public:
void initR(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 rec;
rec.initR(2,3,20,10);
rec.move(3,2);
cout<<"rec(x,y,h,w):"<<endl;
cout<<rec.getX()<<","
<<rec.getY()<<","
<<rec.getH()<<","
<<rec.getW()<<endl;
}
//运行结果为:
//rec(x,y,h,w):
//5,5,10,20
2.私有继承:当类的继承方式为私有继承时,基类的公有成员和保护成员都以私有成员身份出现在派生类中,而基类的私有成员在派生类中不可直接访问。
一般情况下私有继承使用比较少。
例:
#include<iostream>
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() {return x;}
float getY() {return y;}
private:
float x,y;
};
class Rectangle:private Point//私有继承
{
public:
void initR(float x,float y,float w,float h)
{
initP(x,y);
this->w=w;
this->h=h;
}
void move(float xOff,float yOff){Point::move(xOff,yOff);}
float getX() {return Point::getX();}
float getY() {return Point::getY();}
float getH() {return h;}
float getW() {return w;}
private:
float w,h;
};
//main函数与上例完全相同
3.保护继承:保护继承中,基类的公有成员和保护成员都以保护成员身份出现在派生类中,而基类的私有成员不可直接访问。
例:
class A{
protected :
int x;
};
calss B: public A{
public:
void function();
};
void B::function(){
x=5;
}
int main(){
B b;
b.function();
return 0;
}