簡體   English   中英

將派生的 class 轉換為 std::make_shared 中受保護的基本接口時出錯

[英]Error when casting derived class to protected base interface in std::make_shared

我有這個代碼:

#include <memory>

class SomeInterface {
public:
    virtual void VirtualMethod() {}

    virtual void PureVirtualMethod() = 0;
};

class SomeInterfaceDependent {
public:
    explicit SomeInterfaceDependent(SomeInterface* a) : a_(a) {}

private:
    SomeInterface* const a_;
};

class Implementation : protected SomeInterface {
public:
    void Init() {
        // Ok
        auto raw = new SomeInterfaceDependent(this);

        // Cannot cast 'Implementation' to its protected base class 'SomeInterface'.
        auto shared = std::make_shared<SomeInterfaceDependent>(this);

        // Ok
        SomeInterface* casted_some_interface = this;
        auto shared2 = std::make_shared<SomeInterfaceDependent>(casted_some_interface);
    }

protected:
    void PureVirtualMethod() override {}
};


int main() {
    Implementation i;
    i.Init();

    return 0;
}

C++標准17,編譯器GCC。

我收到錯誤error: 'SomeInterface' is an inaccessible base of 'Implementation'當(和):

  • SomeInterface使用受保護的訪問修飾符繼承。
  • SomeInterfaceDependent使用std::make_shared創建。
  • SomeInterface隱式轉換。

為什么? std::make_shared錯誤嗎?

是 std::make_shared 錯誤嗎?

不。

為什么?

std::make_shared不是Implementation的朋友,因此它無法訪問其非公共基礎,因此它不能隱式轉換指針。

受保護的 inheritance 對外部類不公開。

正因為如此,編譯器看不到實現從 SomeInterface 繼承,並且會說它不能進行強制轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM