首页 / C++ / 【C++】44.继承中的访问级别
【C++】44.继承中的访问级别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【C++】44.继承中的访问级别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2271字,纯文字阅读大概需要4分钟。
内容图文
![【C++】44.继承中的访问级别](/upload/InfoBanner/zyjiaocheng/646/e34be8d0c92240da9f6116a6bd114237.jpg)
问题
子类是否可以直接访问父类中的私有成员?
面向对象理论
根据C++语法
example:
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 的意义
- 修饰的成员不能被外界直接访问
- 修饰的成员可以被子类直接访问
class Parent
{
protected:
int mi;
public:
Parent()
{
mi = 100;
}
int value()
{
return mi;
}
};
class Child : public Parent
{
public:
int add(int mv)
{
mi +=mv;
}
};
int main()
{
Parent p;
cout << "p.mv = " << p.value() << endl;
//p.mv = 100 ; // error
Child c;
cout << "c.mv = " << c.value() << endl;
c.add(50);
cout << "c.mv = " << c.value() << endl;
return 0;
}
p.mv = 100
c.mv = 100
c.mv = 150
面向对象的需要protected 原因
(从生活实践中去思考,比如工资并不是不能让别人知道,可以父母知道)
提前思考构造的过程
代码实现如图所示的关系
#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 就无法完成真正意义上的的代码复用
没事尽瞎想 发布了84 篇原创文章 · 获赞 0 · 访问量 593 私信 关注
内容总结
以上是互联网集市为您收集整理的【C++】44.继承中的访问级别全部内容,希望文章能够帮你解决【C++】44.继承中的访问级别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。