继承的概念之前的文章已经提及了,那么子类是否可以直接访问父类的私有成员呢,答案是否定的
例子:
#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 add(int i)
{
mv = mv + i;
}
}
int main()
{
return 0;
}
结果:
a.cpp: 在成员函数‘int Child::add(int)’中:
a.cpp:7:7: 错误: ‘int Parent::mv’是私有的
a.cpp:23:6: 错误: 在此上下文中
a.cpp:7:7: 错误: ‘int Parent::mv’是私有的
a.cpp:23:11: 错误: 在此上下文中
由上可知子类不能直接访问父类的私有成员,这里就要引入我们的访问级别新的访问级别关键字protected
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 add(int i)
{
mv = mv + i;
}
};
int main()
{
Child p;
p.add(100);
cout<<"p.mv = "<<p.value()<<endl;
return 0;
}
结果:
sice@sice:~$ ./a.out
p.mv = 200
可以看出在子类可以直接访问父类中被protected修饰的成员,然而如果我们在main函数加入以下代码就会报错,因为在protected修饰的成员不能被外界直接访问
Parent p;
p.mv = 100;
定义类时访问级别的选择
代码:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Object
{
protected:
string name;
string info;
public:
string getname()
{
return name;
}
string getinfo()
{
return info;
}
};
class Point : public Object
{
private:
int mi;
int my;
public:
Point(int i = 0,int j = 0)
{
ostringstream s;
mi = i;
my = j;
name = "Point";
s<<"P("<<mi<<","<<my<<")"<<endl;
info = s.str();
}
int getMi()
{
return mi;
}
int getYi()
{
return my;
}
};
class Line : public Object
{
private:
Point p1;
Point p2;
public:
Line(Point p3,Point p4)
{
ostringstream s;
p1 = p3;
p2 = p4;
name = "Line";
s << "Line from " << p1.getinfo() << " to " << p2.getinfo();
info = s.str();
}
};
int main()
{
Object o;
Point p(1,2);
Point p1(5,6);
Line l(p,p1);
cout << o.getname() << endl;
cout << o.getinfo() << endl;
cout << endl;
cout << p.getname() << endl;
cout << p.getinfo() << endl;
cout << endl;
cout << l.getname() << endl;
cout << l.getinfo() << endl;
};