2010-06-17 111 views
2

可有人请解释我的错误,我有这个类:范围内的误差

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); 
} 

,但是当我把它叫做:

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; 
} 

我收到错误within context,有人可以解释,为什么?

+1

错误消息只是“在上下文中?”这是运行时错误还是编译时错误?没有其他信息? – 2010-06-17 14:39:13

+7

请留意我给你的建议[上一次](http://stackoverflow.com/questions/3048809/error-in-c-within-context),并看看错误信息的其余部分。 “在上下文中”只是在编译器输出中出现的一行,用于*连接错误的另外两部分。上面是实际的错误,下面是编译器当时正在尝试编译的函数的名称。脱下眼罩,看看更大的图像。 – 2010-06-17 14:39:16

+2

-1不发布整个错误。 – 2010-06-17 14:49:20

回答

8

我想象完整的错误有事情做了“这些成员都是私有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); 
     } 
}; 

然后

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

另一种选择是让printAccount需要参考的帐户(friend printAccount(const Account& account)),然后可以通过参考访问私有变量。

但是,函数名为print 帐户的事实表明它可能更适合作为公共类函数。

+0

非常感谢。很好的回答! – helloWorld 2010-06-17 14:53:27

1

您声明该功能printAccountclass Account的好友。但在该示例中,您正在使用函数reportAccounts访问该类的成员(i->strFirstName ...)。后者没有被宣布为朋友。

+1

事实上,没有理由让printAccount成为你写作的朋友。如果你只是传递printAccount一个const Account&并让它提取它所需的值,那更好。或者让它成为没有参数的成员函数,string print()const。 – 2010-06-17 14:47:45

0

这不应该是整个错误..应该有更多的东西..

由您朋友的语法似乎是正确的方式,但在reportAccounts你似乎使用是私人的Account类的所有领域,如strFirstName和函数的名称是reportAccounts而不是printAccounts所以可能你只是做了一个方法的朋友,但你试图访问另一个私人领域。

1

您在类定义中缺少分号。

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?