第44课 继承中的访问级别

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

 

 

#include<iostream>

using namespace std;


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

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

int main()
{

    return 0;
}

 

 编译出错,那如何访问父类中的非公有成员呢?

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

#include<iostream>

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; //编译会出错。虽然mv的访问级别是protected,但是在外部只有它的子类内部可以直接访问。
    Child c;
    cout << "c.mv = " << c.value() << endl;
    c.addValue(50);
    cout << "c.mv = " << c.value() << endl;
    //c.mv = 200;    //出错
    return 0;
}

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

 

 继承与组合的综合实例:

 

 

#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()
    {
        mX = 0;
        mY = 0;
    }//这个地方也可以不使用这个无参构造函数,直接利用下面的Point(int x=0, int y=0),但是我不知道为什么?
    Point(int x,int y)
    {
        ostringstream s;
        mX = x;
        mY = y;
        s << "p(" << mX << "," << mY << ")" ;
        mName = "Point";
        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();
    }
};
int main()
{
    Object o;
    cout << o.name() << endl;
    cout << o.info() << endl;

    cout << endl;

    Point p(1,2);
    Point pa(5,6);
    cout << p.name() << endl;
    cout << p.info() << endl;

    Line l(p,pa);
    cout << l.name() <<endl;
    cout << l.info() <<endl;
    return 0;
}

小结:
面向对象中的访问级别不只是public和private
protected修饰的成员不能被外界所访问
protected使得子类能够访问父类的成员
protected关键字是为了继承而专门设计的
没有protected就无法完成真正意义上的代码复用

posted @ 2019-11-27 22:13  一代枭雄  阅读(158)  评论(0编辑  收藏  举报