让我们考虑以下代码:
#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()"
}
如果我有上述类,我可以从任何foo
或Base
类实例调用Derived
方法,具体取决于我需要的::foo()
。但是存在某种问题:如果我需要Derived
类实例,但是我需要从此实例调用Base::foo()
方法怎么办?
这个问题的解决可能是下一个: 我将下一个方法粘贴到类Derived
public:
void fooBase()
{
Base::foo();
}
并在我需要来自Derived类实例的Derived::fooBase()
方法时调用Base::foo()
。
问题是我可以使用using
指令执行此操作,如下所示:
using Base::foo=fooBase; //I know this would not compile.
答案 0 :(得分:2)
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) }