【问题标题】:friend of base accesses derived派生的基本访问的朋友
【发布时间】:2012-12-05 10:29:03
【问题描述】:

我遇到了this 未回答的问题,这真的很令人费解。这种行为应该有意义吗?它在标准中吗?这是问题:

class parentFriend;
class parent
{
  friend class parentFriend;
  public: void f1(){};
  protected: void f2(){};
  private: void f3(){};
};
class childpub: public parent {};
class childprot: protected parent {};
class childprv: private parent {};
class parentFriend
{
  public:
  void f()
  {
    /* which of the following statements will compile? why? why not?*/
    parent p; p.f1(); p.f2(); p.f3(); // these will compile 
    childpub cpub; cpub.f1(); cpub.f2(); cpub.f3();
    childprot cprot; cprot.f1(); cprot.f2();
    cprot.f3(); // does not compile 
    childprv cprv;
    cprv.f1(); // does not compile 
    cprv.f2(); // does not compile 
    cprv.f3(); // does not compile 
  }
};

【问题讨论】:

    标签: c++ inheritance encapsulation friend access-control


    【解决方案1】:

    根据我阅读您发布的链接的理解(另请参阅相同的问题here 以及一些答案),原始问题的作者对 gcc 编译器的行为感到惊讶(2009 年的线程,gcc 版本 4.0. 1 在线程中提到)正在编译没有错误这一行,而它不应该有:

    childprot cprot; cprot.f1(); cprot.f2(); // (2)
    

    我在 MSVC 2010 中尝试了您的代码,但此行无法编译,友谊没有按照标准的预期继承。

    【讨论】:

    • 太好了,谢谢。我的 gcc 4.2.4 的行为仍然与原始帖子中的一样。请告诉我除了 cpub.f1() 和 p.f?() 之外的任何东西是否可以编译,因为它们不应该编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2013-08-15
    • 2020-11-24
    • 2017-01-16
    相关资源
    最近更新 更多