派生类的声明
class 派生类名:继承方式 基类名 { 成员声明; }
不同继承方式的影响主要体现在:
派生类成员对基类成员的访问权限
通过派生类对象对基类成员的访问权限
三种继承方式: 公有继承 私有继承 保护继承
公有继承(public):
基类的public和protected成员的访问属性在派生类中保持不变,但基类的private成员不可直接访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员。 通过派生类的对象只能访问基类的public成员。
例:
class Point { //基类Point类的定义
public: //公有函数成员
void initPoint(float x = 0, float y = 0) { this->x = x; this->y = y;}
void move(float offX, float offY) { x += offX; y += offY; }
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) {
initPoint(x, y); //调用基类公有成员函数
this->w = w;
this->h = h;
}
float getH() const { return h; }
float getW() const { return w; }
private: //新增私有数据成员
float w, h;
};
int main() {
Rectangle rect; //定义Rectangle类的对象
//设置矩形的数据
rect.initRectangle(2, 3, 20, 10);
rect.move(3,2); //移动矩形位置
cout << "The data of rect(x,y,w,h): " << endl;
//输出矩形的特征参数
cout << rect.getX() <<", "
<< rect.getY() << ", "
<< rect.getW() << ", "
<< rect.getH() << endl;
return 0;
}
私有继承(private):
基类的public和protected成员都以private身份出现在派生类中,但基类的private成员不可直接访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员。 通过派生类的对象不能直接访问基类中的任何成员。
例:
class Rectangle: private Point { //派生类定义部分
public: //新增公有函数成员
void initRectangle(float x, float y, float w, float h) {
initPoint(x, y); //调用基类公有成员函数
this->w = w;
this->h = h;
}
void move(float offX, float offY) {
Point::move(offX, offY);
}
float getX() const { return Point::getX(); }
float getY() const { return Point::getY(); }
float getH() const { return h; }
float getW() const { return w; }
private: //新增私有数据成员
float w, h;
};
int main() {
Rectangle rect; //定义Rectangle类的对象
rect.initRectangle(2, 3, 20, 10); //设置矩形的数据
rect.move(3,2); //移动矩形位置
cout << "The data of rect(x,y,w,h): " << endl;
cout << rect.getX() <<", " //输出矩形的特征参数
<< rect.getY() << ", "
<< rect.getW() << ", "
<< rect.getH() << endl;
return 0;
}
保护继承(protected):
基类的public和protected成员都以protected身份出现在派生类中,但基类的private成员不可直接访问。 派生类中的成员函数可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员。 通过派生类的对象不能直接访问基类中的任何成员。
protected 成员的特点与作用:
对建立其所在类对象的模块来说,它与 private 成员的性质相同。 对于其派生类来说,它与 public 成员的性质相同。 既实现了数据隐藏,又方便继承,实现代码重用。