0. 問(wèn)題:子類是否可以直接訪問(wèn)父類的私有成員?

1. 繼承中的訪問(wèn)級(jí)別
面向?qū)ο笾械脑L問(wèn)級(jí)別不只是public和private,可以定義protected關(guān)鍵字來(lái)使得修飾的成員不能被外界直接訪問(wèn),可以被子類直接訪問(wèn)。
編程說(shuō)明:protected初探
#include <iostream>
#include <string>
using namespace std;
class Father
{
protected: // protected 關(guān)鍵字
int mValue;
public:
Father()
{
mValue = 100;
}
int value()
{
return mValue;
}
};
class Child : public Father
{
public:
int addvalue(int v)
{
mValue = mValue + v;
return mValue;
}
};
int main()
{
Child c;
cout << c.addvalue(50) << endl;
return 0;
}
輸出結(jié)果:
150
2. 問(wèn)題:為什么面向?qū)ο笾行枰猵rotected?
protected的作用則是實(shí)現(xiàn)繼承。protected成員可以被派生類(也叫子類)對(duì)象訪問(wèn),不能被用戶代碼類外的代碼訪問(wèn)。
3. 定義類時(shí)訪問(wèn)級(jí)別的選擇

4. 組合與繼承的綜合實(shí)例

#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 << "Point(" << 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 " << mP1.info() << ", " << mP2.info() << endl;
mInfo = s.str();
}
};
int main()
{
Point p(1,2);
Point pn(5, 6);
Line l(p, pn);
cout << p.x() << ", " << p.y() << endl;
cout << p.name() << endl;
cout << p.info() << endl;
cout << endl;
cout << l.name() << endl;
cout << l.info() << endl;
return 0;
}
輸出結(jié)果:
1, 2
Point
Point(1, 2)
Line
Line Point(1, 2), Point(5, 6)
5. 小結(jié)
- 面向?qū)ο笾械脑L問(wèn)級(jí)別不只是
public和private -
protected修飾的成員不能被外界所訪問(wèn) -
protected使得子類能夠訪問(wèn)父類的成員 -
protected關(guān)鍵字是為了繼承而專門設(shè)計(jì)的 - 沒(méi)有
protected就無(wú)法完成真正意義上的代碼復(fù)用