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


    学习《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

  • 相关阅读:
    MySQL之存储引擎
    MySQL之触发器
    MySQL之存储过程
    MySQL之自定义函数
    MySQL之视图
    三种方式安装mariadb-10.3.18
    Linux创建智能DNS
    CentOS 7 搭建Cobbler实现自动化安装系统
    搭建PXE实现自动化安装系统
    编译安装dropbear
  • 原文地址:https://www.cnblogs.com/youngkingwang/p/3121007.html
Copyright © 2020-2023  润新知