2012-04-16 68 views
0

假設我有具有2個方法是在結合使用彼此的API:升壓shared_ptr的接口/對象

boost::shared_ptr<IAsset> getAsset(const std::string & id); 
void update(const Asset & asset); 

和我的boost::shared_ptr<Asset> asset在另一個類中的一個成員變量。如果我做的:

asset = otherObject->getAsset("first_asset"); 

// do some stuff 

otherObject->update(*asset); 

我得到的錯誤:

 \boost\include\boost/smart_ptr/shared_ptr.hpp(378): error C2440: '<function-style-cast>' : cannot convert from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>' 
     with 
     [ 
      T=IAsset 
     ] 
     and 
     [ 
      T=Asset 
     ] 
     No constructor could take the source type, or constructor overload resolution was ambiguous 
     src\TestMethod.cpp(35) : see reference to function template instantiation 'boost::shared_ptr<T> &boost::shared_ptr<T>::operator =<IAsset>(boost::shared_ptr<IAsset> &&)' being compiled 
     with 
     [ 
      T=Asset 
     ] 
     \boost\include\boost/smart_ptr/shared_ptr.hpp(378): error C2228: left of '.swap' must have class/struct/union 

我要在這裏指出,對Asset類的定義是延伸IAssetclass Asset : virtual public IAsset {...}

有人能告訴我正確的方法要做到這一點,因爲我無法訪問底層API?

回答

1

我認爲你的繼承使用是不正確的。如果update要求Asset那麼你需要發送一個Asset或其子類。 IAsset是一個超級類。

1

因爲您要將IAsset轉換爲Asset,因此需要向下轉動。

2

這是一個潛在的不安全轉換,因此您必須使用dynamic pointer cast

(請注意,您不能使用虛擬基類中的static_cast。)