上下文中的错误

hel*_*rld 4 c++ oop 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);
}
Run Code Online (Sandbox Code Playgroud)

但是当我打电话给它时:

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;
}
Run Code Online (Sandbox Code Playgroud)

我收到错误within context,有人可以解释原因吗?

jwh*_*ock 9

我想完整的错误与"这些成员是私人的within context"和一些行号有关.

问题是i->strFirstNamereportAccounts()功能的角度看是私有的.更好的解决方案可能是:

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);
        }
};
Run Code Online (Sandbox Code Playgroud)

然后

string reportAccounts() const {
    string report(printAccountsHeader());
    for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
        report += i->print();
    }
    return report;
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是printAccount引用Account(friend printAccount(const Account& account)),然后它可以通过引用访问私有变量.

但是,该函数被称为print account这一事实表明它可能更适合作为公共类函数.