0

正所谓——“朋友不遗传”。
代表着

class c
 {public:
 friend void i_am_friend();
 };

class d:public c
{public:
 //
};

这里 void i_am_friend()不是在类 d 中继承的。用更专业的术语来说(我是这样认为的。)

类 d 的对象不会为void i_am_friend()分配内存,因为它是基类的朋友。
现在考虑问题号。14.3 在这个页面http://www.parashift.com/c++-faq/friends.html

class Base {
 public:
   friend void f(Base& b);
   ...
 protected:
   virtual void do_f();
   ...
 };

 inline void f(Base& b)
 {
   b.do_f();
 }

 class Derived : public Base {
 public:
   ...
 protected:
   virtual void do_f();  // "Override" the behavior of f(Base& b)
   ...
 };

 void userCode(Base& b)
 {
   f(b);
 }

这段代码怎么可能是正确的?因为

class derived d;// d 不会有友元函数
类基 *b=&d; //结果b也没有成员函数

所以在这里调用 f(b) 应该是错误的。

所以说什么是正确的:-
友谊不是继承的
或友谊是继承的,但不能在派生类中使用

4

1 回答 1

2

友谊不是遗传的

即使在您的示例中也是如此。对 f(b) 的调用不应该是一个错误,因为Derived对象被转换为Base&类型。

该函数f只能访问类的私有和受保护部分Base,但只能访问类的公共部分Derived

于 2012-05-18T04:49:01.777 回答