【问题标题】:friend function of the class can't access to its private vector;类的友元函数不能访问其私有向量;
【发布时间】:2012-11-20 13:24:12
【问题描述】:

我有以下声明:

friend ostream& operator<<(ostream&,const List&);

我有以下定义:

ostream& operator<<(ostream& out,const List& item) {
    vector<List::Employee>::const_iterator It;
    for (It=item.employees.begin();It!=item.employees.end();It++) {}
}

Employee是我自己的一个结构体,employees是Employee在List类中的一个私有向量。编译器给了我以下错误:

std::vector<List::Employee,std::allocator<List::Employee>> List::employees is private

有什么办法解决吗?

【问题讨论】:

  • 好友声明在哪里?记住友谊不是遗传的......
  • 在类的公共方法中
  • 一种方法 ??你的意思是类 decl (列表类,顺便说一句)?
  • 是的,我将输出运算符声明为类的友元函数(公开)
  • 朋友声明在哪个类 - 是在List 类还是Employee 类?

标签: c++ private friend


【解决方案1】:

friend 声明应该在 List 类定义中。

class List{
    ...
    friend ostream& operator<<(ostream&,const List&);
};

【讨论】:

  • 很确定这就是 OP 当他说“......它在 List 类中声明”时的意思。
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
相关资源
最近更新 更多