zoukankan      html  css  js  c++  java
  • 关于保护成员的若干问题

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

  • 相关阅读:
    算法设计--求连续子向量的最大和问题--论想法思路的重要性
    --a和a--
    程序员一个知道的一些法则
    django admin
    Python递归
    Python内置函数
    Python协程函数
    Python 生成器
    Python迭代器
    Python装饰器
  • 原文地址:https://www.cnblogs.com/youngkingwang/p/3121007.html
Copyright © 2011-2022 走看看