开发者

C++ - Basic Error with Arrays of Base Classes

开发者 https://www.devze.com 2023-04-13 07:12 出处:网络
I am a bit stuck right now. I have a base class called B开发者_如何学运维aseBond. ZeroCouponBond and CouponBond inherit from that class. I am looking to create an array that contains both types of bon

I am a bit stuck right now. I have a base class called B开发者_如何学运维aseBond. ZeroCouponBond and CouponBond inherit from that class. I am looking to create an array that contains both types of bonds. Here is my code:

...
BaseBond port[12];

for (int i=0; i < recordCount; i++)
{
    if (bonds[i].CouponRate == 0.0)
        port[i] = new ZeroCouponBond(bonds[i]);
    else
        port[i] = new CouponBond(bonds[i]);
}

Here is the error I am getting: error: no match for ‘operator=’ in ‘port[i]

I know this is probably a simple fix and has to do with when I can declare objects in an array, but I'm relatively new to C++ and don't know all the rules.

Thanks in advance for the help!


You need to do this using pointers:

Change the declaration to this:

BaseBond *port[12];

In your original code, you were trying to assign a pointer to BaseBond. So it won't compile.

Furthermore, when you use inheritance like this, you have to do it using pointers anyway to prevent object slicing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号