zoukankan      html  css  js  c++  java
  • C++primer原书中的一个错误(派生类using声明对基类权限的影响)

    在C++primer 第4版的 15章 15.2.5中有以下这样一段提示:
    “注解:派生类能够恢复继承成员的訪问级别,但不能使訪问级别比基类中原来指定的更严格或者更宽松。”
    在vs2010中经过验证。这段话是错误的。详细见下面代码:
    //Base.h
    #pragma once
    #include <iostream>
    using namespace std;
    class Base
    {
    public:
    	Base(void);
    	~Base(void);
    	size_t size()const{return n;}
    protected:
    //private:
    	size_t n;
    };
    

    //Base.cpp
    #include "Base.h"
    
    
    Base::Base(void)
    {
    	n = 100;
    }
    
    
    Base::~Base(void)
    {
    }

    //Derived.h
    #pragma once
    #include "base.h"
    class Derived :
    	private Base
    {
    public:
    	Derived(void);
    	~Derived(void);
    	using Base::size;
    	using Base::n;
    };

    //Derived.cpp
    #include "Derived.h"
    
    Derived::Derived(void)
    {
    }
    
    Derived::~Derived(void)
    {
    }

    //main.cpp
    #include "Base.h"
    #include "Derived.h"
    #include <iostream>
    using namespace std;
    
    void main()
    {
    	Derived XX;
    	Base YY;
    	cout<<XX.size()<<endl;
    	cout<<XX.n<<endl;
    }


    这段程序是能够正常执行没有不论什么错误的。可是基类Base的成员n权限是protected。在派生类中用using将其提权到了public,这就证明了原书中的那段话是错误的。



    可是当我把Base类的protected 成员 n权限改成private的时候却出现了错误,因此推測:仅仅有子类对成员具有訪问权限的时候才干改变成员的訪问级别。


    后来在http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2540.htm看到这样一段话:
    The access rules for inheriting constructors are specified in 12.9 class.inh-ctor; otherwise all All instances of the name mentioned in a using-declaration shall be accessible. In particular, if a derived class uses a using-declaration to access a member of a base class, the member name shall be accessible. If the name is that of an overloaded member function, then all functions named shall be accessible. The base class members mentioned by a using-declaration shall be visible in the scope of at least one of the direct base classes of the class where the using-declaration is specified. ...


    结果证明我的推測是正确的。

  • 相关阅读:
    用AVIFile函数制做AVI文件基本步骤
    RHEL5下源码安装Mysql
    RHEL 6.2/i686配置使用CentOS YUM源
    教你选择最稳定的 MySQL 版本
    RHEL 6.2/i686桌面版解决风扇狂转的问题 安装官方闭源ATI显卡驱动
    Ubuntu 11.10下解决JUK播放MP3乱码的方法
    Ubuntu 10.04下SVN+Apache安装、配置与使用
    Ubuntu 11.10安装(卸载)ATI闭源驱动导致黑屏进不了系统的解决办法
    ubuntu 11.10下创建eclipse桌面快捷方式
    Ubuntu 11.10与Windows双系统的硬盘安装方法
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5113303.html
Copyright © 2011-2022 走看看