# 继承

#### 二.公有继承

``````#include
using namespace std;

class 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() {
return x;
}
float getY() {
return y;
}
private:
float x, y;
};

class Rectangle :public Point {
private:
float w, h;
public:
void initRectangle(float x, float y, float w, float h)
{
initPoint(x, y);
this->w = w;
this->h = h;
}
float getH() { return h; }
float getW() { return w; }
};

int main()
{
Rectangle r;
r.initRectangle(2, 3, 20, 10);
r.move(3, 2);
cout << "The data of r(x,y,w,h):" << endl;
cout << r.getX() << "," << r.getY() << "," << r.getW() << "," << r.getH() << endl;

return 0;
}``````

#### 三.私有继承

``````    void move(float offX, float offY) { Point::move(offX, offY); }
float getX()  { return Point::getX(); }
float getY() { return Point::getY(); }``````

#### 四.保护继承

``````#include
using namespace std;

class A {
protected:
int x;
};
class B :protected A {
public:
void c() { cout << "。。。" << endl; }
};

int main()
{
B a;
a.x;
}``````

#### 总结

1.不管何种继承都不可以访问private成员。
2.派生类只可访问基类公有成员，其他则不可以访问。