基类方法别名

Base class method alias

本文关键字:别名 类方法 基类      更新时间:2023-10-16

让我们考虑以下代码:

#include <iostream>
class Base
{
public:
    void foo() //Here we have some method called foo.
    {
        std::cout << "Base::foo()n";
    }
};
class Derived : public Base
{
public:
    void foo() //Here we override the Base::foo() with Derived::foo()
    {
        std::cout << "Derived::foo()n";
    }
};
int main()
{
    Base *base1 = new Base;
    Derived *der1 = new Derived;
    base1->foo(); //Prints "Base::foo()"
    der1->foo();  //Prints "Derived::foo()"
}

如果我有上述的类,我可以从BaseDerived类实例中的任何一个调用foo方法,这取决于我需要什么::foo()。但是存在某种问题:如果我需要Derived类实例,但我确实需要从该实例调用Base::foo()方法,该怎么办?

这个问题的解决可能是下一步:我将下一个方法粘贴到派生类

public:
void fooBase()
{
    Base::foo();
}

当我需要派生类实例中的CCD_ 8方法时,调用CCD_。

问题是,我能用using指令这样做吗

using Base::foo=fooBase; //I know this would not compile.

der1->Base::foo();  //Prints "Base::foo()"

您可以使用范围解析来调用基类方法,以指定函数版本并解决歧义,这在您不想使用默认解析时很有用。

类似的(不完全相同的情况)例子被提到@cppreference

struct B { virtual void foo(); };
struct D : B { void foo() override; };
int main()
{
    D x;
    B& b = x;
    b.foo(); // calls D::foo (virtual dispatch)
    b.B::foo(); // calls B::foo (static dispatch)
}