从shared_ptr中键入强制转换错误

时间:2012-09-20 10:13:38

标签: c++ shared-ptr

我有以下代码:

namespace {
    class CatBondEvent
    {
    public:
        CatBondEvent(Date date) : date(date){}
        virtual ~CatBondEvent(){}
        Date date;

        bool operator< (CatBondEvent &other) { return date<other.date;}
    };

    class CatEvent : CatBondEvent
    {
    public:
        Real loss;
        CatEvent(Date date, Real loss) : CatBondEvent(date), loss(loss) {}
    };

    class CollateralCoupon : CatBondEvent
    {
    public:
        Real unitAmount;
        CollateralCoupon(Date date, Real unitAmount) : CatBondEvent(date), unitAmount(unitAmount) {}
    };

    class CatBondCoupon : CatBondEvent
    {
    public:
        CatBondCoupon(Date date) : CatBondEvent(date) {}
    };

    void fillEvents(std::vector<boost::shared_ptr<CatBondEvent> > &events, 
                    Date startDate,
                    Date endDate,
                    boost::shared_ptr<std::vector<std::pair<Date, Real> > > catastrophes, 
                    boost::shared_ptr<Bond> collateral,
                    boost::shared_ptr<std::vector<Date> > couponDates)
    {
        for(int i=0; i<catastrophes->size(); ++i) 
        {
            events.push_back(boost::shared_ptr<CatBondEvent>(new CatEvent((*catastrophes)[i].first, (*catastrophes)[i].second)));
        }
        const Leg& cashflows = collateral->cashflows();
        for(int i=0; i<cashflows.size() && cashflows[i]->date()<=endDate; ++i) 
        {
            boost::shared_ptr<CashFlow> cashflow = cashflows[i];
            if(cashflow->date() >= startDate)
            {
                events.push_back(boost::shared_ptr<CatBondEvent>(new CollateralCoupon(cashflow->date(), cashflow->amount())));
            }
        }
        for(int i=0; i<couponDates->size(); ++i) 
        {
            Date couponDate = (*couponDates)[i];
            if(couponDate >= startDate)
            {
                events.push_back(boost::shared_ptr<CatBondEvent>(new CatBondCoupon(couponDate)));
            }
        }
    }
}

我收到以下编译错误:

Error   37  error C2243: 'type cast' : conversion from '`anonymous-namespace'::CollateralCoupon *' to '`anonymous-namespace'::CatBondEvent *' exists, but is inaccessible   c:\boost\boost_1_49_0\boost\smart_ptr\shared_ptr.hpp    184
Error   36  error C2243: 'type cast' : conversion from '`anonymous-namespace'::CatEvent *' to '`anonymous-namespace'::CatBondEvent *' exists, but is inaccessible   c:\boost\boost_1_49_0\boost\smart_ptr\shared_ptr.hpp    184
Error   38  error C2243: 'type cast' : conversion from '`anonymous-namespace'::CatBondCoupon *' to '`anonymous-namespace'::CatBondEvent *' exists, but is inaccessible  c:\boost\boost_1_49_0\boost\smart_ptr\shared_ptr.hpp    184

知道出了什么问题以及如何解决它?

1 个答案:

答案 0 :(得分:5)

您的继承是私有的,这会阻止从指向派生类的指针转换为指向其基类的指针。您可能想要公共继承:

class CatEvent : public CatBondEvent
                 ^^^^^^

除非另有说明,否则对使用class关键字定义的类中的成员和基类的访问是私有的,而使用struct定义的类中的public是访问。