友谊与传承

时间:2019-03-28 21:34:46

标签: c++ inheritance friend

我正在做一个小项目,我有点困惑,因为我不太了解友谊和继承是如何相互作用的。我将向您展示一些示例代码。

namespace a
{
    class Foo
    {
    public:
        Foo(int x) : m_x(x) {}
    protected:
        friend class b::Derived;
        friend class a::Base;
        int m_x;
    };

    class Base
    {
    public:
        Base(Foo foo) : m_foo(foo) {}
    protected:
        Foo m_foo;
    };
}
namespace b
{
    class Derived : public a::Base
    {
    public:
        Derived(a::Foo foo)
            : Base(foo)
        {
            m_foo.m_x;
        }
    };
}
e0265: at line 29: member a::Foo::m_x (declared at line 10) is inaccessible

显然Derived无法访问Foo的受保护成员,这似乎是因为Derived :: m_foo是派生成员,因此构造Derived将失败。谁能向我详细解释一下?

2 个答案:

答案 0 :(得分:0)

  

貌似派生无法访问Foo的私有成员   因为Derived :: m_foo是派生成员,所以构造Derived   将失败。

对不起,这显然不是对朋友的误解。

朋友班级可以访问任何属性。

您有一个不相关的编码错误...这些注释表明您缺少Base中的(Base :: m_foo)初始化。修复此问题,向Foo添加一些数据项,然后运行演示:

#include <iostream>
using std::cout, std::endl; 

class Foo
{
public:
   Foo(int x): m_x(x){}
   ~Foo(){}

   int m_z;   // add public

protected:
   int m_y;   // add protected

private:      // change to private
   friend class Derived;
   int m_x;
};

class Base
{
public:
   Base() : m_foo(0) // add m_foo Initialization (with 0)
      {}
   virtual ~Base(){}
protected:
   Foo m_foo;
};

class Derived : public Base
{
public:
   Derived(Foo foo)
      {
         foo.m_y   = 11;
         foo.m_z   = 22;
         std::cout << foo.m_x << "   "
                   << foo.m_y << "   "
                   << foo.m_z << std::endl;  //friend class can access
      }
};

class T914_t // ctor and dtor compiler provided defaults
{
public:
   int operator()(int argc, char* argv[]) { return exec(argc, argv);  }

private: // methods

   int exec(int , char** )
      {
         Foo     f(99);
         Derived d(f);

         return 0;
      }

}; // class T914_t

int main(int argc, char* argv[]) { return T914_t()(argc, argv); } // call functor

类派生的ctor的典型输出,用于访问私有,受保护和公共数据属性:

  

99 11 22

答案 1 :(得分:0)

我发现了问题。名称空间b以及因此派生的类对Foo中的好友声明不可见。当我转发声明b并派生所有内容时,一切按预期方式工作,派生可以访问私有/受保护的成员。

相关问题