C++继承中的访问级别

1 C++继承中的访问级别

1.1 protected访问级别

思考一下:子类是否可以直接访问父类的私有成员?
在这里插入图片描述
继承中的访问级别:

  • 面向对象中的访问级别不只是public和private。
  • 可以定义protected访问级别。
  • 关键字protected的意义:
    • 修饰的成员不能被外界直接访问。
    • 修饰的成员可以被子类直接访问。

protected关键字就是为了继承而专门设计的,没有protected就无法完成真正意义上的代码复用。

protected示例代码:

#include <iostream>
#include <string>

using namespace std;

class Parent
{
protected:
    int mv;
public:
    Parent()
    {
        mv = 100;
    }
    
    int value()
    {
        return mv;
    }
};

class Child : public Parent
{
public:
    int addValue(int v)
    {
        mv = mv + v;    
    }
};

int main()
{   
    Parent p;
    
    cout << "p.mv = " << p.value() << endl;
    
    // p.mv = 1000;    // error
    
    Child c;
    
    cout << "c.mv = " << c.value() << endl;
    
    c.addValue(50);
    
    cout << "c.mv = " << c.value() << endl;
    
    // c.mv = 10000;  // error
    
    return 0;
}

1.2 定义类时访问级别的选择

定义类时访问级别的选择如下:
在这里插入图片描述

1.3 组合与继承的综合实例

在这里插入图片描述

#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 << "P(" << 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 from " << mP1.info() << " to " << mP2.info();
        
        mInfo = s.str();
    }
    Point begin()
    {
        return mP1;
    }
    Point end()
    {
        return mP2;
    }
};

int main()
{   
    Object o;
    Point p(1, 2);
    Point pn(5, 6);
    Line l(p, pn);
    
    cout << o.name() << endl;
    cout << o.info() << endl;
    
    cout << endl;
    
    cout << p.name() << endl;
    cout << p.info() << endl;
    
    cout << endl;
    
    cout << l.name() << endl;
    cout << l.info() << endl;
    
    return 0;
}


参考资料:

  1. C/C++从入门到精通-高级程序员之路【奇牛学院】
  2. C++深度解析教程
发布了271 篇原创文章 · 获赞 28 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/SlowIsFastLemon/article/details/104252313
今日推荐