can somebody please explain my mistake, I have this class:
class Account
{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
friend string printAccount(string firstName, string lastName, int id, int lines, double lastBill);
}
but when I call it:
string reportAccounts() const
{
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i)
{
report += printAccount(i->strFirstName, i->strLastName, i->nID, i->nLines, i->lastBill);;
}
return report;
}
I receive error within context
, can somebody explain why?
I imagine the full error has something to do with "These members are private within context
" and some line numbers.
The issue is that i->strFirstName
is private from the perspective of the reportAccounts()
function. A better solution may be:
class Account{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
string print() const
{
return printAccount(this->strLastName, this->strFirstName, this->nID,
this->nLines, this->lastBill);
}
};
And then
string reportAccounts() const {
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
report += i->print();
}
return report;
}
Another option is to make printAccount
take a reference to an Account (friend printAccount(const Account& account)
), and it can then access the private variables through the reference.
However, the fact that the function is called print Account suggests that it might be better as a public class function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With