weixin_38941602 2018-07-05 03:15 采纳率: 33.3%
浏览 1070
已结题

C++继承含有友元函数的基类后,子类对象模型问题

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对象找到基类中 == 操作符函数的。

也可以给我推荐一下关于这方面的书籍,深入友元内部实现的。

  • 写回答

2条回答 默认 最新

  • weixin_40864484 2018-07-05 03:24
    关注

    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;
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看