c++第四次作业
继承与派生
1.定义
在C++语言中,一个派生类可以从一个基类派生,也可以从多个基类派生。从一个基类派生的继承称为单继承;从多个基类派生的继承称为多继承。
2.派生类的声明
class 派生类名:继承方式 基类名
{
生类成员的声明
}
3.继承方式
1) 公有继承(public)
公有继承的特点是基类的公有成员和保护成员作为基类的成员时,它们都保持原有的状态,而基类的私有成员仍然是私有的,不能被这个派生类的子类所访问。
例子:
#include<iostream> using namespace std; class Point { private: float x, y; public: void initP(float x, float y) { 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; } }; 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() const { return h; } float getW()const { return w; } private: float w, h; }; int main() { rectangle rect; rect.initR(2, 3, 20, 10); rect.Move(3, 2); cout << rect.getX() << "," << rect.getY() << "," << rect.getW() << "," << rect.getH() << endl; return 0; }
结果:

2) 私有继承(private)
私有继承的特点是基类的公有成员和保护成员都作为派生类的私有成员,并且不能被这个派生类的子类所访问。
3) 保护继承(protected)
保护继承的特点是基类的所有公有成员和保护成员都成为派生类的保护成员,并且只能被它的派生类成员函数或友元访问,基类的私有成员仍然是私有的。
浙公网安备 33010602011771号