我使用定義的接口庫:成員函數指針
template<class desttype>
void connect(desttype* pclass, void (desttype::*pmemfun)());
,我有一個小的層次
class base {
void foo();
};
class derived: public base { ... };
在derived
一個成員函數,我想致電
connect(this, &derived::foo);
但似乎&derived::foo
實際上是一個成員函數指針的base
; GCC吐出
error: no matching function for call to ‘connect(derived* const&, void (base::* const&)())’
我可以明確地鑄造this
到base *
解決這個問題;但爲什麼編譯器不能匹配desttype = base
的調用(因爲derived *
可以隱式轉換爲base *
)?
另外,爲什麼是&derived::foo
不是成員函數指針derived
?
是否有真的很好理由使用指向成員函數的指針,而不是僅僅在基礎中聲明(純?)虛函數,並在需要時調用它? – 2010-04-08 18:01:40
@Jerry,你是什麼意思? – 2010-04-08 18:13:06
@傑裏棺材:當有 - 有。調用純虛函數的唯一方法是通過該函數的硬編碼名稱。當硬編碼特定函數不可接受時,使用指向成員的指針。這一定是這種情況之一。 – AnT 2010-04-08 18:15:29