2013-02-13 34 views
0

我有兩個用戶自定義類:我怎麼投用戶定義的類的指針,而無需使用繼承

class A:class Base 
{ 
type x; 
doSomething(); 
} 

class B 
{ 
type x; 
doSomething(); 
} 

我也有一個功能,它獲取類型庫的變量,並使用dynamic_cast將其轉換爲鍵入A並使用doSomething()。

class D : class Base2 
{ 
    D(Base _base1):Base2(Base _base1) 
    { 
     //here is the actual problem 
    } 
    void foo() 
    { 
     //b is a private member of class Base2 of type Base 
     A *a=dynamic_cast(b); 
     A->doSomething(); 
    } 
} 

但我想傳遞B到這個函數,並且同時我不希望B繼承自Base。

p.s我無權更改基地

這怎麼可能?

+0

你不這樣做。請參閱[嚴格別名](http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule)爲什麼。 – WhozCraig 2013-02-13 07:22:56

回答

3

在不安全的無關類之間進行投射。實現我認爲你想要做的最安全的方法是使用函數模板:

template <typename T> 
void foo(const T& b) 
{ 
    b.doSomething(); 
} 
+1

+1關於這個問題可以想象的最簡單的解決方案。 – WhozCraig 2013-02-13 07:25:42

+0

讓我編輯問題 – Shohreh 2013-02-13 07:41:56

相關問題