简体   繁体   中英

C++ - Basic Error with Arrays of Base Classes

I am a bit stuck right now. I have a base class called BaseBond. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM