![](/img/trans.png)
[英]Design base class for derived classes with functions having different signatures
[英]Accessing hidden functions from base classes with different signatures
我們有:
class A {
public:
int f();
int f(int);
//...
};
class B {
public:
int f();
int f(int);
//...
};
class AB : public A, public B {
public:
long f(double, double);
//...
};
A::f()
, A::f(int)
, B::f()
, B::f(int)
現在隱藏在class AB
,我只想使用A::f()
和B::f(int)
好像它們沒有被隱藏:
AB ab;
ab.f(); // ab.A::f()
ab.f(1); // ab.B::f(1)
有沒有比編寫以下代碼更簡單的方法來實現此目的?
class AB : public A, public B {
public:
//...
int f() {return A::f();}
int f(int x) {return B::f(x);}
};
我想到過using
關鍵字,但是它不能區分具有相同名稱和不同簽名的方法。
唯一的方法是聲明它們,並在編寫時調用所需的基類函數。
您可能已經考慮過以某種奇怪的方式使用“ using”例如: using A::f
; 但是您繼承具有相同功能的所有函數簽名,並且不能指定單個簽名。
AB類聲明中的內容是:
您從兩個基類都獲得了接口和實現,在調用這兩個基類上都通用的方法時會出錯(注意!即使簽名不一樣)。 theABVar.A::f();
會給你:
錯誤:“對成員'f'的請求不明確”
但是您可以使用theABVar.A::f();
解決此問題theABVar.A::f();
(這很酷嗎?:D)
基類中的成員被隱藏了,因此,對該方法的調用不再歧義。
但是要在基類上調用方法,您應該執行與以前相同的技巧。
theABVar.f();
會給你
Ettor:沒有匹配的函數可以調用“ AB :: f()”
當您嘗試對基類函數使用“ using”時,即使您不使用該函數,也將獲得編譯時間:
使用A :: f; 使用B :: f;
using聲明'using B :: f'與先前的using聲明沖突
無論如何,請三思而后行。
您需要一個函數,它根據參數的數量/類型調用不同基類的成員? 我無法想象在很多情況下這是有道理的。
- - - - - - - 結論 - - - - - - - -
theABVar.A::f()
, theABVar.A::f(3)
, theABVar.B::f()
, theABVar.B::f(3)
, theABVar.AB::f(3.0,3.0)
和theABVar.f(3.0,3.0)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.