44_继承中的访问级别

0. 问题:子类是否可以直接访问父类的私有成员?

1. 继承中的访问级别

面向对象中的访问级别不只是publicprivate,可以定义protected关键字来使得修饰的成员不能被外界直接访问可以被子类直接访问

编程说明:protected初探

#include <iostream>
#include <string>

using namespace std;

class Father
{
protected:          // protected 关键字
     int mValue;
public:
    Father()
    {
        mValue = 100;
    }
    
    int value()
    {
        return mValue;
    }
};

class Child : public Father
{
public:
    int addvalue(int v)
    {
        mValue = mValue + v;
        return mValue;
    }
};

int main()
{
    Child c;
    
    cout << c.addvalue(50) << endl;
    
    
    return 0;
}

输出结果:

150

2. 问题:为什么面向对象中需要protected?

protected的作用则是实现继承。protected成员可以被派生类(也叫子类)对象访问,不能被用户代码类外的代码访问。

3. 定义类时访问级别的选择

4. 组合与继承的综合实例

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class Object
{
protected:
    string mName;
    string mInfo;
public:
    Object()
    {
        mName = "Object";
        mInfo = "";
    }
    
    string name()
    {
        return mName;
    }
    
    string info()
    {
        return mInfo;
    }
};

class Point : public Object
{
private:
    int mX;
    int mY;
public:
    Point(int x = 0, int y = 0)
    {
        ostringstream s;
        mX = x;
        mY = y;
        mName = "Point";
        
        s << "Point(" << mX << ", " << mY << ")";
        
        mInfo = s.str();        
    }
    
    int x()
    {
        return mX;
    }
    
    int y()
    {
        return mY;
    }
};

class Line : public Object
{
private:
    Point mP1;
    Point mP2;
public:
    Line(Point p1, Point p2)
    {
        ostringstream s;
        mP1 = p1;
        mP2 = p2;
        mName = "Line";
        
        s << "Line " << mP1.info() << ", " << mP2.info() << endl;
        mInfo = s.str();    
    }
};

int main()
{
    Point p(1,2);
    Point pn(5, 6);
    
    Line l(p, pn);
    
    cout << p.x() << ", " << p.y() << endl;
    cout << p.name() << endl;
    cout << p.info() << endl;
    
    cout << endl;
    
    cout << l.name() << endl;
    cout << l.info() << endl;

    return 0;
}

输出结果:

1, 2
Point
Point(1, 2)

Line
Line Point(1, 2), Point(5, 6)

5. 小结

  • 面向对象中的访问级别不只是publicprivate
  • protected修饰的成员不能被外界所访问
  • protected使得子类能够访问父类的成员
  • protected关键字是为了继承而专门设计的
  • 没有protected就无法完成真正意义上的代码复用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容