Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an error within context

Tags:

c++

oop

class

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?

like image 522
helloWorld Avatar asked Dec 22 '22 02:12

helloWorld


1 Answers

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.

like image 132
jwhitlock Avatar answered Jan 04 '23 23:01

jwhitlock