如何为.cpp文件中的私有类成员定义友元运算符<<而不是在标题中?

问题描述 投票:0回答:1

编译此代码失败:

class P {
//public:
  class C {
  friend std::ostream& operator<<(std::ostream &os, const C &c);
  };
};


std::ostream& operator<<(std::ostream &os, const P::C &c) {
  return os;
}

错误:

test.cpp:12:53: error: 'C' is a private member of 'P'
std::ostream& operator<<(std::ostream &os, const P::C &c) {
                                                    ^
test.cpp:6:9: note: implicitly declared private here
  class C {
        ^
1 error generated.

取消注释public:使这个代码编译。它显然可以转移到班级本身。

但是在私有成员类的cpp文件中定义这样的operator<<的正确方法是什么?

c++ stream operator-overloading inner-classes friend
1个回答
3
投票

要查看P的私人元素,您的operator<<必须是P的朋友。所以为了能够访问类C的定义:

class P {
  class C {
      ...
  };
  friend std::ostream& operator<<(std::ostream &os, const C &c);
};

然后,您当前的操作员将编译。但它只能访问C的公共成员,因为它是封闭的P的朋友,但不是嵌套的C的朋友:

std::ostream& operator<<(std::ostream &os, const P::C &c) {
  return os;
}

如果您还需要访问C的私人会员,您需要成为双重朋友:

class P {
  class C {
    int x;   //private 
    friend std::ostream& operator<<(std::ostream &os, const C &c);  // to access private x
  };
  friend std::ostream& operator<<(std::ostream &os, const C &c); // to access private C
};

std::ostream& operator<<(std::ostream &os, const P::C &c) {
  os<<c.x; 
  return os;
}
© www.soinside.com 2019 - 2024. All rights reserved.