为什么我不能在"好友"运算符中使用"私人"字段?
Why I can't use the `private` field in the `friend` operator?
头文件有它:
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;
}
}
}
相关文章:
- 将结构字段的类型展开为可变模板参数
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 私有字段对象与私有继承?
- 声明没有默认构造函数的字段
- C++内存模型和位字段的最大序列
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 如何通过UDP接收QByteArray并将其解析为位字段结构?
- 仅匹配集合中的某些字段
- 结构字段名称与 GDB 中的 STL 数组冲突
- 如何使用位字段将数据从二进制文件复制到结构中?
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何避免在数据结构中包含存储为字段的类?
- 好友功能 - 无法访问私人字段C++
- 为什么我不能在"好友"运算符中使用"私人"字段?