獲取一些非常令人困惑的錯誤,但不確定原因。這裏是我的代碼:C++ - 何時正確使用 - >?錯誤:' - >'的基本操作數具有非指針類型'BaseBond'
//=====================WORKS=======================
TradingBook::TradingBook(const char* yieldCurvePath, const char* bondPath)
{
//...Some stuff
BaseBond* tradingBook[bondCount];
for (int i=0; i < bondCount; i++)
{
tradingBook[i] = new CouponBond(bonds[i]);
printf("Bond: %s\n"
" Price: %.3f\n"
" DV01: %.3f\n"
" Risk: %.3f\n", tradingBook[i]->getID(), tradingBook[i]->getPrice(), tradingBook[i]->getDV01(), tradingBook[i]->getRisk());
}
}
//=================DOESNT WORK======================
//Gives Error: base operand of ‘->’ has non-pointer type ‘BaseBond’
void TradingBook::runAnalytics()
{
for (int i=0; i < bondCount; i++)
{
tradingBook[i]->calcPrice(tradingBook[i]->getYield());
tradingBook[i]->calcDV01();
tradingBook[i]->calcRisk();
printf("Bond: %s\n"
" Price: %.3f\n"
" DV01: %.3f\n"
" Risk: %.3f\n", tradingBook[i]->getID(), tradingBook[i]->getPrice(), tradingBook[i]->getDV01(), tradingBook[i]->getRisk());
}
}
我得到的錯誤基礎操作「 - >」具有在每個實例非指針類型「BaseBond」 - >,但只在runAnalytics()方法。 tradingBook是一個公共類變量。爲什麼它會在底部方法中給我一個錯誤,而不是構造函數?我不明白。
我也嘗試在第二種方法中將tradingBook [i] - > method()更改爲tradingBook [i] .method(),但它給了我一個分段錯誤,所以我認爲這是不對的。任何人都可以幫我澄清我的困惑嗎?
在情況下,它是需要的,這裏是頭文件TradingBook:
class TradingBook
{
public:
TradingBook(const char* yieldCurvePath, const char* bondPath);
double getBenchmarkYield(short bPeriods) const;
BaseBond* tradingBook;
int treasuryCount;
Treasury* yieldCurve;
int bondCount;
void runAnalytics();
};
BaseBond是一個抽象類。它的孩子是CouponBond和ZeroCouponBond。 tradingBook [i]充滿了這兩種類型。這裏是BaseBond的標題:
class BaseBond{
public:
virtual double getPrice() = 0;
virtual double getYield() = 0;
virtual short getPeriods() = 0;
virtual char* getID() = 0;
virtual double getDV01() = 0;
virtual double getRisk() = 0;
virtual char* getRateType() = 0;
virtual void calcPrice(double nyield) = 0;
virtual double calcPriceR(double nyield) const = 0;
virtual void calcDV01() = 0;
virtual void calcRisk() = 0;
};
在預先感謝您,stackOverFlow!
可能重複的[Operator'。' vs' - >'in C++](http://stackoverflow.com/questions/7344127/operator-vs-in-c) –