1、值得思考的问题
- 子类是否可以直接访问父类的私有成员?
1、根据面向对象的理论:

2、根据C++语法:

实验检验:
#include <iostream>
#include <string>
using namespace std;
class Parent
{
int i;
public:
Parent(int i = 0)
{
this->i = i;
}
int getI()
{
return i;
}
};
class Child : public Parent
{
public:
int func(int v)
{
i = i + v;
return i;
}
};
int main()
{
return 0;
}

所以,在这里我们得出结论,子类不能访问父类的私有成员,有没有什么方法可以使子类能访问父类的私有成员?
2、继承中的访问级别
- 面向对象中的访问级别不只是 public 和 private
- 可以定义 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;
return mv;
}
};
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;
}

把父类原本 private 的私有成员的访问级别改成 protected ,这样在子类的成员函数里面就可以访问父类的私有成员。但是在外部依旧无法访问私有成员。
3、思考
-
为什么面向对象中需要 protected ?
答:因为面向对象的思想来源于生活,生活中我们有些信息是可以让别人知道,比如学历,对应于面向对象中的 public;有些信息是可以不想让别人知道,比如年龄,对应于面向对象中的 private;有些信息可以让身边的亲人知道,但不想让外界知道,比如工资,于是引入新的访问级别—— protected -
定义类时访问级别的选择:

4、组合和继承的综合实例

结论:有继承关系的父类访问级别一般设置成 protected,没有继承关系的类访问级别一般设置成 private
#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 oss;
mX = x;
mY = y;
mName = "Point";
oss << "P(" << mX << " , " << mY << ")";
mInfo = oss.str();
}
};
class Line : public object
{
private:
Point mP1;
Point mP2;
public:
Line(Point P1, Point P2)
{
mP1 = P1;
mP2 = P2;
mName = "Line";
ostringstream oss;
oss << "Line from " << mP1.info() << " to " << mP2.info() << endl;
mInfo = oss.str();
}
};
int main()
{
object o;
Point p(1, 2);
Point pp(5, 6);
Line L(p, pp);
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;
cout << endl;
return 0;
}

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

被折叠的 条评论
为什么被折叠?



