友元继承的疑问
有这种说法:
a friend function is not inherited. i.e. when a base class includes a
friend function, that friend is not a friend of a derived class
于是在vc中试运行如下代码
#include <iostream>
using namespace std;
class A
{
public:
int x,y;
friend ostream& operator < <(ostream& os, A& a)
{
os < < "x= " < <a.x < < ";y= " < <a.y < <endl;
return os;
}
};
class B :public A
{
};
int main(void)
{
B b;
cout < <b;
return 0;
}
并没有出现编译问题,那么是否违反了上面的规则呢?不知道c++的规定究竟是怎样的,上哪里可以查到呢?
[解决办法]
没有违反,这里可以的原因是:B类型的对象可以赋给A类型的引用。而对于你的那个operator < <,它所看到的仍然只是个A类型的引用,它根本不知道当前引用的对象并不是A类型的,而是A的派生类的。