C++primer原書中的一個錯誤(衍生類別using聲明對基類許可權的影響),primerusing

來源:互聯網
上載者:User

C++primer原書中的一個錯誤(衍生類別using聲明對基類許可權的影響),primerusing
在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. ...


結果證明我的猜測是正確的。
對如下基類與衍生類別的聲明,指出下列每個例子的錯誤(6分)

(1)Derived d; d.foo(1034); //1034是int類型的資料,而Derived 類的foo函數資料類型為string
(2)bool Derived::bar(Base *pb){return foo_bar == pb->foo_bar;} //pb是Base類,而Base類中pb->foo_bar的這個成員是私人的,在Derived類的bar函數中顯然無法調用。
 
對於虛基類的成員在最衍生類別中的存取權限的疑問?

虛基類和非虛基類的繼承本來就沒有太大區別:
僅在如你圖所給的關係中,非虛基類會有多個副本而產生歧異,而虛基類繼承過來只有一個副本。

有公有許可權的就以公有許可權為先!然後保護許可權!
私人不能繼承

cout<<d.B::funA()<<endl; //沒有d.B::funA()這種調用方式 這是錯的

再者,很少有私人繼承和保護繼承!
圖示的繼承的方式,也很少見,多以組合等取代之
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.