![](/img/trans.png)
[英]Returning make_shared<Base>, inheritence and casting to Derived not working as expected?
[英]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'
當(和):
std::make_shared
創建。 為什么? 是std::make_shared
錯誤嗎?
是 std::make_shared 錯誤嗎?
不。
為什么?
std::make_shared
不是Implementation
的朋友,因此它無法訪問其非公共基礎,因此它不能隱式轉換指針。
受保護的 inheritance 對外部類不公開。
正因為如此,編譯器看不到實現從 SomeInterface 繼承,並且會說它不能進行強制轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.