C++错误:'operator='不匹配

C++ Error: No match for 'operator='

本文关键字:不匹配 operator 错误 C++      更新时间:2023-10-16

为数组赋值时出现问题。我创建了一个名为Treasury的类。我创建了另一个名为TradingBook的类,我希望它包含一个Treasury的全局数组,该数组可以从TradingBook中的所有方法访问。这是我的TradingBook和Treasury的头文件:

class Treasury{
public:
    Treasury(SBB_instrument_fields bond);
    Treasury();
    double yieldRate;
    short periods;
};

class TradingBook
{
public:
    TradingBook(const char* yieldCurvePath, const char* bondPath);
    double getBenchmarkYield(short bPeriods) const;
    void quickSort(int arr[], int left, int right, double index[]);
    BaseBond** tradingBook;
    int treasuryCount;
    Treasury* yieldCurve;
    int bondCount;
    void runAnalytics(int i);
};

这是我得到错误的主要代码:

TradingBook::TradingBook(const char* yieldCurvePath, const char* bondPath)
{
    //Loading Yield Curve
    // ...
    yieldCurve = new Treasury[treasuryCount];
    int periods[treasuryCount];
    double yields[treasuryCount];
    for (int i=0; i < treasuryCount; i++)
    {
        yieldCurve[i] = new Treasury(treasuries[i]);
        //^^^^^^^^^^^^^^^^LINE WITH ERROR^^^^^^^^^^^^^^
    }
}

我得到错误:

'yieldCurve[i] = new Treasury(treasuries[i]);' 线上的'operator='不匹配

有什么建议吗?

这是因为yieldCurve[i]的类型是Treasury,而new Treasury(treasuries[i]);是指向Treasury对象的指针。所以你有一个类型不匹配。

尝试更改此行:

yieldCurve[i] = new Treasury(treasuries[i]);

到此:

yieldCurve[i] = Treasury(treasuries[i]);
    Treasury* yieldCurve;

yieldCurve是指向Treasury的数组的指针,而不是指向Treasury*的指针。在出现错误的行处删除new,或者修改声明使其成为指针数组。