本文共 1441 字,大约阅读时间需要 4 分钟。
C++继承机制概述
不论是哪种继承方式,这三个核心概念都在起作用:公有继承、私有继承以及保护继承。各类继承方式决定了派生类对基类成员的访问权限,从而影响代码的封装性和维护性。
以公有继承的例子为例,子类对基类的继承方式决定了对成员的访问权限。默认情况下,不同的继承方式会带来不同的访问权限规则。
以下是一个使用多继承模型的典型例子:
代码摘录:
#includeusing namespace std;class Point {public: void setxy(int myx, int myy) { X = myx; Y = myy; } void movexy(int x, int y) { X += x; Y += y; }protected: int X, Y;};class Circle : public Point {public: void setr(int myx, int myy, int myr) { setxy(myx, myy); R = myr; } void display() { cout << "The position of center is("; cout << X << ")"; cout << " and y coordinate is "; cout << Y << ")"; cout << "The radius of Circle is "; cout << R << endl; }protected: int R;};void Circle::display() { cout << "The position of center is(" << X << ")"; cout << " and y coordinate is "; cout << Y << ")"; cout << "The radius of Circle is "; cout << R << endl;}
代码解释:
执行结果:
上述代码展示了公有继承方式的典型应用,验证了我们在多继承模型中对访问权限的控制。通过合理设计继承层次,有助于提高代码的可维护性和复用性。
转载地址:http://nbirz.baihongyu.com/