基类中的protected成员可以被派生类访问,具体是指:在派生类的定义或声明中,成员函数通过派生类的对象访问定义的protected成员。但是不能在程序中直接访问。

具体见下面的例子

 

#include <iostream>
using namespace std;

class item_base
{
public:
 item_base(int x,int y):xx(x),yy(y) {}
protected:
 int yy;
private:
 int xx;
};
class bulk_item:public item_base
{
public:
 bulk_item(int x,int y):item_base(x,y) {}
 
 int gety(bulk_item &b,item_base &i)
 { 
  cout<<b.yy<<endl;  //正确:因为派生类只能通过派生类对象访问其基类的protected成员。只能在类的定义或声明中访问protected成员。
 // cout<<i.yy<<endl;  //错误:因为派生类对其基类对象的protected成员没有特殊访问权限。
  cout<<yy<<endl;
  return 0;
 }
};


int main()
{
 bulk_item c(3,4);
 bulk_item b(5,6);
 item_base i(1,2);
 b.gety(c,i);
// cout<<i.yy<<endl; //错误:在程序中,protected成员不能被访问,也就是不能通过对象(基类或派生类的)访问。只能在上述类的声明或定义中访问。
 return 0;
}