1.值得思考的问题
- 子类是否可以直接访问父类的私有成员?
- 根据面向对象的理论:子类拥有父类的一切属性和行为,子类能够直接访问父类的私有成员!
- 但C++语法规定,外界不能直接访问类的private成员,所以子类也不能直接访问父类的私有成员!
#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; // error如何访问父类的非公有成员
return mv;
}
};
int main()
{
return 0;
}
2.继承中的访问级别
- 面向对象中的访问级别不只是public和private,可以定义protected访问级别
- 关键字protected的意义
- 修饰的成员不能被外界直接访问
- 修饰的成员可以被子类直接访问
- 原则:
- 需要被外界访问的成员直接设置为public
- 只能在当前类中访问的成员设置为private
- 只能在当前类和子类中访问的成员设置为protected
- private成员在子类中依然存在,但是却无法访问到
3.编程实验
- protected初体验
#include<iostream>
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;
return mv;
}
};
int main()
{
Parent p;
cout << "p.mv = " << p.value() << endl;
Child c;
cout << "c.mv = " << c.value() << endl;
c.addValue(50);
cout << "c.mv = " << c.value() << endl;
system("pause");
return 0;
}
- 运行结果:
4.组合和继承的综合实例
- Point,Line与Object是继承关系,Point和Line是组合关系
#include<iostream>
#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;
system("pause");
return 0;
}
运行结果
- 组合和继承,都是类之间的一种关系。只不过在性质和使用方式上存在不同。、
5.小结
- 面向对象中的访问级别不只有public和private
- protected修饰的成员不能被外界所访问
- protected使得子类能够访问父类的成员
- protected关键字是为了继承而专门设计的
- 没有protected就无法完成真正意义上的代码复用