【问题标题】:friend for private class私人课程的朋友
【发布时间】:2014-05-13 08:19:03
【问题描述】:

私教如何定义好友?

#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"; }

如何在类/结构定义之外做到这一点?

【问题讨论】:

  • 下一篇没有行号的代码,拜托!

标签: c++ friend


【解决方案1】:

虽然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.

【讨论】:

    【解决方案2】:

    Priv_t 的重载必须是 Base_t 和 Priv_t 的朋友。

    【讨论】:

      【解决方案3】:

      友谊必须是明确的:

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

      【讨论】:

        猜你喜欢
        • 2022-11-13
        • 2011-08-07
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        相关资源
        最近更新 更多