为什么我不能在"好友"运算符中使用"私人"字段?

Why I can't use the `private` field in the `friend` operator?

本文关键字:私人 字段 运算符 不能 好友 为什么      更新时间:2023-10-16

头文件有它:

class Shape_definition {
private:
    // ...
    std::vector<Instruction> items;         
public:
    //...
    friend std::istream& operator >> (std::istream& is, Shape_definition& def); // FRIEND!
};
//-----------------------------------------------------------------------------
std::istream& operator >> (std::istream& is, Shape_definition& def);
//...

定义代码:

std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def){
    //...
    Bushman::shp::Instruction instr = Bushman::shp::Instruction::get_empty();
    while(is >> instr) def.items.push_back(instr); // Problem is here!
    return is;
}

但我在MS Visual Studio编辑器中遇到了一个错误:

错误C2248:"Bushman::shp::Shape_definition::items":无法访问在类"Bushman::shp::Shape_definition"中声明的私有成员

为什么我不能在friend运算符中使用private字段?

谢谢。

经过一些检测工作,我假设Shape_definition是在命名空间中定义的,std::istream& operator >> (std::istream& is, Shape_definition& def);的声明也是如此。

然后在命名空间之外定义另一个std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def)。由于这不是你的朋友,访问被阻止。

尝试将其定义为:

namespace Bushman
{
  namespace shp
  {
    std::istream& operator >> (std::istream& is, Bushman::shp::Shape_definition& def){
        //...
        Bushman::shp::Instruction instr = Bushman::shp::Instruction::get_empty();
        while(is >> instr) def.items.push_back(instr); // Problem is here!
        return is;
    }
  }
}