9

我是初学者级别的面向对象编程爱好者。我遇到了以下难题:

class A { 
}; 

class B { 
protected: 
    friend class A; 
};

class C { 
public: 
    friend class B; 
};

参考上面的示例代码,假设上面的类都有数据成员,那么在声明A的成员时可以使用C的哪些成员名称?

  1. 仅限私人会员

  2. 只有受保护的成员

  3. C 的所有数据成员

  4. 仅限公众成员

  5. 没有 C 的数据成员*

我的选择是答案 4,因为友谊不是传递的。因此,A 是 B 的朋友,但 A 不是 C 的朋友(即使 B 是 C 的朋友)。这是正确的想法吗?

另外,我的问题是到目前为止(在教程中)我遇到了这样声明友谊的例子:

class X { 
public: 
    friend class Y;
};

如果我们使用受保护的说明符而不是公共说明符,有什么区别?像那样:

class X { 
protected: 
    friend class Y; 
};
4

1 回答 1

7
  1. You are correct. Friendship is not transitive nor is it Inherited.
  2. It does not make any difference under what access specifier you put the friend declaration.

As long as class A itself is not declared friend of class C. You cannot access any protected or private members of C in A.

于 2013-01-17T12:21:45.000 回答