简体   繁体   English

C ++-基类数组的基本错误

[英]C++ - Basic Error with Arrays of Base Classes

I am a bit stuck right now. 我现在有点卡住了。 I have a base class called BaseBond. 我有一个名为BaseBond的基类。 ZeroCouponBond and CouponBond inherit from that class. ZeroCouponBond和CouponBond继承自该类。 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] 这是我得到的错误:错误:'port [i]中的'operator ='不匹配

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. 我知道这可能是一个简单的修复,并且与我在数组中声明对象的时间有关,但我对C ++相对较新,并且不了解所有规则。

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 . 在原始代码中,您尝试为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. 此外,当您使用这样的继承时,无论如何都必须使用指针来进行,以防止对象切片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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