标签:综合 代码复用 include color value 代码 min 疑惑 nbsp
1、面向对象中的访问级别不只是public和private
2、可以定义protected的访问级别
3、关键字protected的意义
(1)、修饰的成员不能被外界直接访问
(2)、修饰的成员可以被子类直接访问
#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, protected Child c; cout << "c.mv = " << c.value() << endl;//继承了父类的成员函数 c.addValue(50); cout << "c.mv = " << c.value() << endl; // c.mv = 10000; // error, protected return 0; }
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; mName = "Point"; mX = x; mY = y; s << "p(" << mX << "," << mY << ")"; mInfo = s.str(); } }; class Line : public Object { private: Point mP1;//Line 由 Point 组合而成 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;//Object cout << o.info() << endl; cout << endl; cout << p.name() << endl;//Point cout << p.info() << endl;//p(1, 2) cout << endl; cout << l.name() << endl;//Line cout << l.info() << endl;//Line fromP(1, 2)toP(5, 6) return 0; }
1、面向对象的访问级别不只public和private
2、protected修饰的成员不能被外界直接访问
3、protected使得子类能够访问父类的成员
3、protected关键字为了继承而专门设计的
4、没有protected就无法完成真正意义上的代码复用
标签:综合 代码复用 include color value 代码 min 疑惑 nbsp
原文地址:http://www.cnblogs.com/gui-lin/p/6367223.html