文章目录
一、值得思考的问题
子类是否可以直接访问父类的私有成员?
- 思考过程
下面来看一个继承中的访问级别:
#include <iostream>
#include <string>
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 的意义
- 修饰的成员不能被外界直接访问
- 修饰的成员可以被子类直接访问
下面来进行 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;
}
输出结果如下,注意 p.mv = 1000; 和 c.mv = 10000; 都会报错,因为 protected 修饰的成员不能被外界直接访问,但是 c.addvalue(50); 不会报错,这是因为 protected 修饰的成员可以被子类直接访问
三、定义类时访问级别的选择
思考:为什么面向对象中需要 protected ?
公开的信息用 public,隐私的信息,不想被外界知道,用 private, 有的东西可以让一部分人知道,这个时候就得用 protected
四、组合与继承的综合实例
Point 和 Line 都继承于 Object 这个类,Line 这个类需要组合两个 point 类,因为两点确定一条直线。
下面来进行实现:
#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;
}
输出结果如下:
五、小结
- 面向对象中的访问级别不只是 public 和 private
- protected 修饰的成员不能被外界所访问
- protected 使得子类能够访问父类的成员
- protected 关键字是为了继承而专门设计的
- 没有 protected 就无法完成真正意义上的代码复用