1

头文件有它:

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”中声明的私有成员

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

谢谢你。

4

1 回答 1

5

经过一些侦探工作,我假设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;
    }
  }
}
于 2013-07-25T08:28:17.440 回答