我正在研究一个小项目,我有点卡住,因为我真的不明白友谊和继承如何相互作用。我将向您展示一些示例代码。
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将失败。任何人都可以向我详细解释这个吗?
显然,Derived无法访问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
Derived ctor类的典型输出访问私有,受保护和公共数据属性:
99 11 22
我发现了这个问题。名称空间b以及派生的类对于Foo中的朋友声明是不可见的。当我转发声明b和派生的所有工作按预期和派生可以访问私人/受保护的成员。