关于c ++友谊和VC12和VC14继承的不同行为

时间:2016-09-21 08:47:17

标签: c++ visual-studio inheritance friend

class Base 
{
protected:
    void func1();
};

class Derived : public Base
{
friend class Third;
};

class Third
{
     void foo() 
     {
        Derive d;
        d.func1();
     }
};

我可以在VC14(Visual Studio 2015)中编译代码而不会出错 但从VC12(Visual Studio 2013)

获取错误
cannot access protected member declared in class 'Base'
谁是对的? 具有继承权的这种自由的正确性是什么?

来自MSDN https://msdn.microsoft.com/en-us/library/465sdshe.aspxhttp://en.cppreference.com/w/cpp/language/friend看起来这种友谊不是传递性的,无法继承。但是我认为这个代码示例的情况并非如此。

但为什么VC14不会给我一个错误?

如果VC14是对的,我怎样才能修改"代码,以便VC12也可以吗? 在Derived?中再次定义受保护的func1()?

1 个答案:

答案 0 :(得分:4)

修正拼写错误后,内联评论:

class Base 
{
protected:
    void func1();   // protected access
};

class Derived : public Base
{
  // implicit protected func1, derived from Base

  // this means 'make all my protected and private names available to Third'
  friend class Third;
};

class Third
{
     void foo() 
     {
        Derived d;
        // func1 is a protected name of Derived, but we are Derived's friend
        // we can therefore access every member of Derived
        d.func1();
     }
};

VC14是正确的。

VC12的可能解决方法:

class Base 
{
protected:
    void func1();
};

class Derived : public Base
{
  protected:
    using Base::func1;

  private:
    friend class Third;
};


class Third
{
     void foo() 
     {
        Derived d;
        d.func1();
     }
};

另一种可能的解决方法(使用基于密钥的访问)

class Third;
class Func1Key
{
  private:
    Func1Key() = default;
    friend Third;
};

class Base 
{
protected:
    void func1();
};

class Derived : public Base
{
public:  
  void func1(Func1Key) 
  {
    Base::func1();
  }
};


class Third
{
     void foo() 
     {
        Derived d;
        d.func1(Func1Key());
     }
};