關於error: assignment of data-member ‘A::pCost’ in read-only structure的問題
Class A : public B
{
public:
void Initialise(void);
void GetCost( const CostType & cost ) const;
protected:
double* pCost;
};
void A::Initialise(void)
{
double iniCost[12] = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 };
pCost = iniCost;
}
void GetCost( const CostType & cost ) const
{
double updatedCost[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
updatedCost = cost;
pCost = updatedCost; // 此行報錯:error: assignment of data-member ‘A::pCost’
}
請教問題出在哪里?
需求是在A::Initialise初始化pCost指針,使其指向一個初始數組,然后在GetCost函數中更新pCost指向的數組。
函數GetCost( const CostType & cost ) const中的const無法去掉(可以去掉嗎?),A繼承自B得來。
謝謝!
6 个解决方案
updatedCost = cost;
這句話也有毛病
updatedCost是一個固定地址不能做左值
而且updatedCost這是一個局部變量,函數調用完,這樣使pCost變成野指針
毛病太多。。。。。
如果沒有理解const的話,最好是不要亂用...會帶來很多不必要的麻煩
void GetCost( const CostType & cost )
const;
謝謝幾位回答!
現在有幾個問題:
1. A類由B類繼承,在B類中,void GetCost( const CostType & cost )
const; 是virtual虛函數。如果在A類中需要覆蓋,可以去掉
const嗎?
2. 如果在A類中,void GetCost( const CostType & cost )
const必須為const函數,其無法修改成員變量pCost,但是我記得好像是可以
通過指針進行修改,請問具體怎么做?
3. 如youkuxiaobin提出的兩個問題,
updatedCost是一個固定地址不能做左值和
pCost變成野指針。現在我的需求是調用Initialise初始化pCost指針,然后每次調用GetCost修改pCost指向的數組,請問代碼該怎么改?