Hi All,
I'm hoping someone can help me with this error and what I am doing wrong, I've spent an entire day trying to get to grips with it but concede I need help. Googling and searching the forums returns threads where the code is inconsistent in declaring one part of the code constant and elsewhere not.
I thought that, if I pass a reference to an object into a function and declare it constant, I would still be able to use accessor functions of the object that are constant themselves?
The Hop class below has some accessor functions which are declared constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Hop{
public:
Hop();
~Hop();
std::string GetDescription() const {return itsDescription;}
float GetAA() const {return itsAA;}
float GetWeight() const {return itsWeight;}
float GetBoilTime() const {return itsBoilTime;}
void SetDescription(std::string s) {itsDescription = s;}
void SetAA(float fAA) {itsAA = fAA;}
void SetWeight(float fWeight) {itsWeight = fWeight;}
void SetBoilTime (float fBoilTime) {itsBoilTime = fBoilTime;}
private:
std::string itsDescription;
float itsAA;
float itsWeight;
float itsBoilTime;
};
|
In the main code I use a vector of class hop and load it with details from a text file (code not included)
I have a function 'Hop EnterHoppingDetails(const Hop &myHop)' which I have added the keyword const to make it constant since I am only calling member functions of type constant from the hop reference passed in.
each call to GetDescription(), GetAA(), GetWeight(), GetBoilTime() all generate the compile error
main.cpp:148:49: error: passing ‘const Hop’ as ‘this’ argument of ‘const string Hop::GetDescription()’ discards qualifiers [-fpermissive]
ie the line
cout << "Hop: " << myHop.GetDescription() << endl;
Your help to understand what I have done wrong will be greatly appreciated.
Cheers,
Wayne.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
Hop EnterHoppingDetails(const Hop &myHop)
{
// used by Add and Edit a hop before passing back modified hop object
// adjust hop AA, weight, boil time
string sTemp;
Hop updatedHop = myHop;
float fNewAA;
float fNewWeight;
float fNewBoilTime;
bool bValidNumber = true;
// set AA
do {
cout << "Hop: " << myHop.GetDescription() << endl;
cout << "Alpha Acid - return to accept or type new AA: " << myHop.GetAA() << " " ;
getline(cin, sTemp);
if (sTemp.length() > 0)
{
// New AA entered, cast to float
bValidNumber = StringToFloat(sTemp, fNewAA);
if (bValidNumber == true && fNewAA > 0 && fNewAA < 50 )
{
updatedHop.SetAA(fNewAA);
} else
{
bValidNumber = false;
}
}
} while (bValidNumber == false);
cout << "Hop Alpha Acid: " << updatedHop.GetAA() << endl;
|