-
November 3rd, 2010, 06:38 AM
#1
About "error: assignment of data-member ‘A::pCost’ in read-only structure".
About "error: assignment of data-member ‘A:Cost’ in read-only structure".
Hi there,
I got an error as above.
My requirements are: I need a derived class A from class B. In A, there are two member functions, i.e., Initialise() and GetCost(). The Initialise() initialises pointer pCost pointing to an array, and every invocation of GetCost() change the array pCost pointing to.
1. I know that a const function GetCost() can not change the value of the member variable, e.g., pCost. However, I think there is a way to use pointer to solve the problem but I don't know how to do it.
2. The GetCost() in class A is overriden from a virtual function in class B. Can I remove the 'const' after the function?
The codes are shown below, and any suggestions would be appreciated.
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; // error as well
pCost = updatedCost; // error: assignment of data-member ‘A:Cost’
}
-
November 3rd, 2010, 06:46 AM
#2
Re: About "error: assignment of data-member ‘A::pCost’ in read-only structure".
Arrays are not directly assignable. You either need to wrap the array in a class or struct (which are assignable), or else you need to copy them element-by-element, possibly using std::copy().
-
November 3rd, 2010, 07:15 AM
#3
Re: About "error: assignment of data-member ‘A::pCost’ in read-only structure".
Thanks for your reply!
Can I do something like:
Class A : public B
{
public:
void Initialise(void);
void GetCost( const CostType & cost ) const;
~A();
protected:
mutable double m_Cost[12];
};
void A::Initialise(void)
{
double iniCost[12] = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0 };
m_Cost = iniCost;
}
void GetCost( const CostType & cost ) const
{
m_Cost = cost;
}
-
November 3rd, 2010, 07:40 AM
#4
Re: About "error: assignment of data-member ‘A::pCost’ in read-only structure".
This is the line which doesn't work. Arrays are not assignable.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|