版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42187898/article/details/84328773
如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux
第四十四课 继承中的访问级别
1.值得思考的问题
子类是否可以直接访问父类的私有成员?可以,protected关键字替换private即可
2.思考过程
根据面向对象理论:
根据C++语法:
44-1 继承中的访问级别—此程序有报错—如何访问父类中的非公有成员?
#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; // How to access non-public members in a parent class?
}
};
int main()
{
return 0;
}
3.继承中的访问级别
面向对象中的访问级别不只是public和private
可以定义protected访问级别
关键字protected的意义
修饰的成员不能被外界直接访问
修饰的成员可以被子类直接访问
44-2 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 = 100
c.mv = 100
c.mv = 150
4.思考
为什么面向对象中需要protected?
5.定义类时访问级别的选择
6.组合与继承的综合示例
44-3 综合实例
#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;
}
运行结果
Object
Point
P(1, 2)
Line
Line from P(1, 2) to P(5, 6)
小结
面向对象中的访问级别不只是public和private
protected修饰的成员不能被外界所访问
protected使得子类能够访问父类的成员
protected关键字是为了继承而专门设计的
没有protected就无法完成真正意义上的代码复用