如何在 .cpp 文件中为私有类成员定义 friend 运算符<<而不是在标头中


编译

此代码失败:

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<<的正确方法是什么?

要查看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;
}

最新更新