template
class less{
friend bool operator==(const T& l, const T& r);
public:
less() {}
~less() {}
};
class point : less
{
friend bool operator< (const point& l, const point& r);
point () {}
~point() {}
private:
int x;
};
void main()
{
point one(5);
point two(6);
cout << (one < two) << endl;
cout << (one == two) << endl;
cin.get();
}
手动定义了< 操作符,而继承了一个定义了 == 的友元模板函数的模板类(为了简洁点,函数定义我这里没给出)。
求教各位大神,为什么在 one == two 执行时,编译器会找到 less 类的 == 函数中去,子类point中定义了一个friend < 操作符函数,而 less中定了一个 == 的模板函数,继承的是point的一个实例。
简化一下我的问题,我想透彻了解一下编译器调用函数的行为,如何通过子类point对象找到基类中 == 操作符函数的。
也可以给我推荐一下关于这方面的书籍,深入友元内部实现的。
primer上明确说,友元是不能继承的。
但是,若是使用派生类实参为基类实参复制,这种情况下还是可以成功执行友元函数的。
代码如下:
#include //③验证友元的继承
using namespace std;
class A
{
public:
friend void f(A *p);
A()
{
n=0;
}
virtual void display()
{
cout<<"hello world A"<<endl;
}
protected:
int n;
};
void f(A *p)
{
cout<n<<endl;
}
class B:public A
{
public:
B():A() { m=0; }
virtual void display()
{
cout<<"hello world B"<<endl;
}
protected:
int m;
};
int main()
{
B b;
A *a=&b;
a->display(); //调用B类的display
a->A::display(); //调用A类的display
A &aa=b;
aa.display(); //调用B类的display
aa.A::display(); //调用A类的display
A a1;
A *p=&a1;
f(p);
B b1;
p=&b1;
f(p);
return 0;
}