2012-04-16 63 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。)