c ++ using-declarations用于从基类调用函数

tes*_*ram 0 c++

为什么要d.f(1)调用Derived::f此代码?

是否using Base::f决定其发挥作用f将被调用?

#include <iostream>
using namespace std;

struct Base {
    void f(int){
        cout << "\n f(Base) is called" ;
    }
};
struct Derived : Base {
    using Base::f ;    //  using-declarations  but still Drived function is called
    void f(int){
        cout << "\n f(Derived) is called" ;
    }
};
void use(Derived d)
{

    d.f(1);     // calls Derived::f
    Base& br = d ;
    br.f(1);        // calls Base::f
}

int main() {

        Derived d;
        use (d);
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 5

该函数 void f(int)在派生类隐藏函数中的碱,因为它们具有相同的名称和参数.

这里解释:Using-declaration将基类的成员引入派生类定义,例如将base的受保护成员公开为derived的公共成员.在这种情况下,nested-name-specifier必须命名所定义的基类.如果名称是基类的重载成员函数的名称,则引入具有该名称的所有基类成员函数.如果派生类已具有具有相同名称,参数列表和限定条件的成员,则派生类成员将隐藏或覆盖(不冲突)从基类引入的成员.