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, d开发者_开发问答ouble 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.
You're declaring that function printAccount
is friend of class Account
. But in the example, you're accessing the members of the class (i->strFirstName
...) in the function reportAccounts
. This latter is not declared as friend.
You are missing a semicolon in the class definition.
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);
};
^--- see the semicolon here?
That shouldn't be the whole error.. there should be something more..
by the way your friend syntax seems correct, but in reportAccounts
you seem to use all the fields of Account
class that are private, like strFirstName
and the name of the function is reportAccounts
not printAccounts
so probably you just made a method friend but you are trying to access private fields with another one.
精彩评论