友谊和派生类 [英] Friendness and derived class

查看:122
本文介绍了友谊和派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类层次结构:

Let's say I have the following class hierarchy:

class Base
{
  protected:

    virtual void foo() = 0;

    friend class Other;
};

class Derived : public Base
{
  protected:

    void foo() { /* Some implementation */ };
};

class Other
{
  public:

    void bar()
    {
      Derived* a = new Derived();

      a->foo(); // Compiler error: foo() is protected within this context
    };
};

我想我也可以改变它 a-> Base :: foo (),但因为 foo()是在 Base 类中的纯虚函数,将会导致调用 Derived :: foo()无论如何。

I guess I could change it too a->Base::foo() but since foo() is pure virtual in the Base class, the call will result in calling Derived::foo() anyway.

然而,编译器似乎拒绝 a-> foo()。我想这是合乎逻辑的,但我不能真正理解为什么。我缺少什么?不能(不应该)处理这个特殊情况吗?

However, the compiler seems to refuse a->foo(). I guess it is logical, but I can't really understand why. Am I missing something ? Can't (shouldn't) it handle this special case ?

谢谢。

推荐答案

当您使用类名限定方法名时,如 Base :: foo()动态分派(运行时绑定) 。它将总是调用基本实现 foo() c $ c> foo()是否是虚拟的。因为在这种情况下它是纯虚拟的,没有实现,编译器抱怨。

When you qualify a method name with a class name, as in Base::foo() dynamic dispatch (run-time binding) does not apply. It will always call the Base implementation of foo(), no matter if foo() is virtual or not. Since in this case it is pure virtual, there is no implementation and the compiler complains.

你的第二个问题是,在C ++中,友谊不会继承。如果您要其他 Derived 有特殊访问权限,则需要是

Your second problem is that in C++, friendship is not inherited. If you want Other to have special access to Derived, it needs to be a friend of Derived specifically.

这是另一方面,工作原理:

This, on the other hand, works:

Base* a = new Derived();

a->foo(); 

因为这里调用 foo() Base * 其中 foo()是公开的,并且因为您不符合资格 foo()带有类名,它使用动态分派并最终调用 Derived 版本 Foo

Because here, you are calling foo() on a Base* where foo() is public, and since you are not qualifying foo() with a class name, it uses dynamic dispatch and ends up calling the Derived version of Foo.

这篇关于友谊和派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆