這個問題在這里已經有了答案: 為什么宣告私有基類會使型別名稱無法訪問? (1 個回答) 2 天前關閉。
我遇到了一個問題,我以某種方式設法解決了這個問題,但仍然想了解該語言及其背后的推理。我有以下三個班級的系統:
檔案 class_a.hpp
#pragma once
class A
{
public:
A();
};
檔案 class_b.hpp
#pragma once
#include "class_a.hpp"
class B : A
{
public:
B() : A() {}
virtual double do_something(A &with_object) const;
};
檔案 class_c.hpp
#pragma once
#include "class_b.hpp"
class C : B
{
public:
C() : B() {}
double do_something(::A &with_object) const; // but differently than class B
};
現在,如果我不在AC 的do_something()方法中使用型別的完全限定名稱,我仍然會在編輯器中收到以下錯誤:
型別“A::A”(在“class_a.hpp”的第 27 行宣告)是不可訪問的 C/C (265)
What could be possible causing any ambiguity in this case? I certainly haven't redefined or used the name A as an identifier. Is there something happening in the background that makes use of the class name?
Also is the override of the do_something() method guaranteed to work this way, or is qualifying the type A in the B's method also required?
Any advice and/or pointers are also greatly appreciated!
uj5u.com熱心網友回復:
除了繼承的其他內容之外,還有注入類名。你可以把它們看作是隱藏的型別別名:里面class A有類似的東西using A = A;,指向自己。
請記住,private默認情況下是類繼承。
由于B從A私有繼承,C無法訪問 的內容A,其中包括A的注入類名。
do_something()方法的覆寫是否保證以這種方式作業,或者是否還需要A在B's 方法中限定型別?
是的,覆寫B是有效的。由于直接B繼承自,因此可以訪問其所有內容,無論繼承是否為私有。A
您的代碼類似于以下內容。我用實際的型別別名替換了注入的類名,并得到了相同的行為。
class A
{
public:
using A_type = A;
};
class B : A
{
public:
virtual double do_something(A_type &with_object) const;
};
class C : B
{
public:
double do_something(A_type &with_object) const;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/345009.html
