1、值得思考的问题
1.1、
根据面向对象的理论:
子类拥有父类的一切属性和行为
,子类能够直接访问父类的私有成员!
1.2、
但C++语法规定,外界
不能直接访问类的private
成员,所以
子类也不能直接访问父类的私有成员
!
2、继承中的访问级别
2.1、
面向对象中的访问级别不只是public和private
2.2、
可以定义protected访问级别
2.3、
关键字
protected
的意义
2.3.1、
修饰的成员
不能被外界直接访问
2.3.2、
修饰的成员
可以被子类直接访问
为什么面向对象中需要protected关键字???
定义类时访问级别的选择::
组合和继承的综合实例:
/*********************** 组合和继承的综合实例 ***********/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//ostringstream 将数字转换为字符串
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: //没有子类,无须被访问,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(); //将s这个数字转换为字符串
}
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 = "mLine";
s << "Line from" << mP1.info() << "to " << mP2.info();//利用组合使用他们私有变量,父类调用方法
mInfo = s.str();
}
Point begin()
{
return mP1;
}
Point end()
{
return mP2;
}
};
int main()
{
Object o; //调用构造方法
Point pb(1, 2);
Point pe(5, 6);
Line l(pb, pe);
cout << o.name() << endl;
cout << o.info() << endl;
cout << endl;
cout << pb.name() << endl;
cout << pb.info() << endl;
cout << pe.info() << endl;
cout
<<
pe
.
name
()
<<
endl
;
cout << endl;
cout << l.name() << endl;
cout << l.info() << endl;
return 0;
}
3、小结
3.1、
面向对象中的访问级别不只有public和private
3.2、
protected
修饰的成员
不能被外界所访问
3.3、
protected
使得
子类能够访问父类的成员
3.4、
protected关键字是为了继承而专门设计的
3.5、
没有protected就无法完成真正意义上的代码复用