44-继承中的访问级别
来源:互联网 发布:人工智能优势好处 编辑:程序博客网 时间:2024/05/16 09:24
1、疑问
不能
2、思考
#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;}编译错误,不能访问父类私有成员
3、继承中的访问级别
要想实现子类能够访问父类成员变量,可以将私有成员变量改为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 main函数为类的外部,不能够直接访问类内的保护成员 Child c; cout << "c.mv = " << c.value() << endl; c.addValue(50); cout << "c.mv = " << c.value() << endl; // c.mv = 10000; // 不能在类的外部直接修改protacted成员 return 0;}
4、思考
5、定义类时访问级别的选择
6、组合与继承的示例
#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;}ObjectPointP(1, 2)LineLine from P(1, 2) to P(5, 6)
7、小结
阅读全文
0 0
- 44-继承中的访问级别
- c++中的成员访问级别和派生继承方式
- Swift中的访问级别
- 继承中的三种访问级别——学习c++笔记
- 继承类成员的访问级别
- JAVA中的访问控制级别
- 继承中的访问顺序
- Java中的四种访问级别
- 继承就是全部的包含,级别只说明访问权限
- 访问级别
- 访问级别
- 访问级别
- C++语法基础--恢复继承成员的访问级别,默认继承保护级别,友元关系与继承,继承与静态成员
- java中的继承与对象的访问
- C++学习之继承中的访问控制
- 继承中的访问权限修饰符
- C++继承中的成员访问控制
- C++ 中的访问权限与继承方式
- python中字符串一些基础方法的使用
- Nginx的优点
- 你的流量加密尚需功能再升级
- 2017.10.30 学习笔记
- 基于数据库的分布式消息队列
- 44-继承中的访问级别
- java实现excel下载和上传的工具类
- 选数
- 程序员平常加班严重,如何有效率的提升自己?
- How HBO’s Silicon Valley built “Not Hotdog” with mobile TensorFlow, Keras & React Native
- 在MySQL中创建实现自增的序列(Sequence)的教程
- iOS算法总结-选择排序
- webpack插件
- by