私人班的朋友

时间:2014-05-13 08:19:03

标签: c++ friend

如何为私人课程定义朋友?

#include <iostream>

class Base_t{
    private:
        struct Priv_t{
            friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj);
        } p;
    friend std::ostream & operator<<(std::ostream &os, const Base_t& obj);
};

std::ostream & operator<<(std::ostream &os, const Base_t& obj) {
    return os << "base: " << obj.p;
}

std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
    return os << "priv";
}

int main() {
    Base_t b;
    std::cout << b << std::endl;
}

错误:

:!make t17 |& tee /tmp/vB5G5ID/54
g++     t17.cpp   -o t17
t17.cpp: In function 'std::ostream& operator<<(std::ostream&, const Base_t::Priv_t&)':
t17.cpp:5:16: error: 'struct Base_t::Priv_t' is private
         struct Priv_t{
                ^
t17.cpp:15:59: error: within this context
 std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
                                                           ^
make: *** [t17] Error 1

shell returned 2

当我在Priv_t

中直接定义朋友时,它可以正常工作
 friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj) { return os << "priv"; }

如何在类/结构定义之外执行此操作?

3 个答案:

答案 0 :(得分:3)

虽然Priv_t是私人声明,但您应该移动

friend std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj);

进入Base_t

class Base_t
{
private:
  struct Priv_t
  {
  } p;
  friend std::ostream & operator<<(std::ostream &os, const Base_t& obj);
  friend std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj);
};

Live code.

答案 1 :(得分:1)

Priv_t的重载必须是Base_t以及Priv_t的朋友。

答案 2 :(得分:1)

友谊必须明确:

class Base_t
{
//...
private:
    //... 
    // Add:
    friend std::ostream & operator<<(std::ostream &os, 
                                               const Base_t::Priv_t& obj);
};