C++学习笔记43——protected访问标识符

来源:互联网 发布:java 选择语句 编辑:程序博客网 时间:2024/04/29 18:44

1,访问标识符汇总



定义在protected标号之后的成员可以被类成员(成员函数)、友元、和派生类成员访问。类的普通用户不能访问protected成员。

2,继承与保护

难点在于这一句话:
派生类只能通过派生类对象访问基类的protected成员,派生类对其基类类型对象的protected成员没有特殊访问权限。

自己的理解:
1,假设基类father中有一个protected成员叫test,不管是数据成员还是函数成员,由于继承,其派生类son获得了一个一样的protected成员test;
2,一个类,只有在其成员函数的定义体中才能使用自己的protected成员,用户代码中无法使用;
3,所以,在基类father的成员函数定义中可以使用基类的protected成员;
4,同样,在派生类son的成员函数定义体中可以使用son的protected成员,这个成员可能是继承自father类的;
5,但是,在派生类son的成员函数定义体中不能通过引入一个father类的对象来使用father类的protected成员;

例子如下:
/*******************************************************************///   protected/*******************************************************************/class apple{public:apple(string col, double wei) :color(col), weight(wei) {};public :string color;protected:double weight;};class Father{protected:void test() { printf("Father:test()\n"); }};class Son : public Father{public:void bTest() { //用的是从父类继承而来的,自己的protected成员test(); //protected成员在此处可用 this->test();} //错误的成员函数定义//void bTest_new(Father& f)//{////用的是父类的protected成员//f.test(); ////error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)//}};//mainint main(){//1, 在用户代码中不可见apple fushi("red", 50);cout << fushi.color << endl;//cout << fushi.weight << endl;// error C2248 : “apple::weight” : 无法访问 protected 成员(在“apple”类中声明)//2, 在子类的成员函数中Father f;Son s;//f.test(); //error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)//s.test(); //error C2248: “Father::test”: 无法访问 protected 成员(在“Father”类中声明)s.bTest();  //bTest为public}


0 0
原创粉丝点击