• 关于保护成员的若干问题


    学习《TCPL》时,遇到了一个保护成员方面的问题。

    问题代码:

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class A{
     6 protected:
     7     char a[128];
     8 public:
     9     A(){}
    10     ~A(){}
    11 };
    12 class B:public A{};
    13 class c: public A{
    14     void f(B* p) {
    15     a[0] = 0;
    16     p->a[0] = 0;//error:access to protected member of different type
    17     }
    18 };
    19 int main()
    20 {
    21     
    22     return 0;
    23 }
    View Code

     用g++编译,出现编译错误:

    class.cc: In member function ‘void c::f(B*)’:
    class.cc:7:15: error: ‘char A::a [128]’ is protected
    class.cc:16:5: error: within this context

    分析:

      在第16行中,p本意是想访问B中的保护成员A::char a[128],但是因为B 和 C都是从A继承过来的,所以,A::char a[128]对于C 来说也是C中的保护成员,故:

        在C的作用域的范围内,A::char a[128]只能被C中的成员函数访问,因为p是一个B对象,故p在C中不能访问A::char a[128]

    参考:

      链接1

      也可参考《TCPL》 P404 15.3.1

  • 相关阅读:
    0806 c#总复习
    0804 递归
    0808 html基础
    0803结构体,枚举类型
    0801out传值
    0731函数
    0730特殊集合
    0728多维数组,ArrayList集合
    js 获取url链接的任意参数
    jq dom操作
  • 原文地址:https://www.cnblogs.com/youngkingwang/p/3121007.html
Copyright © 2020-2023  润新知