用C++隐藏基类中所有重载方法的同名方法

在C++中,函数重载是可能的,即来自同一类的两个或多个函数可以具有相同的名称,但不同的参数。但是,如果派生类重新定义了基类成员方法,那么具有相同名称的所有基类方法都将隐藏在派生类中。

null

例如,以下程序不编译。在这里,派生重新定义了Base的方法fun(),这使得fun(int i)隐藏起来。

CPP

// CPP Program to demonstrate derived class redefines base
// class member method and generates compiler error
#include <iostream>
using namespace std;
class Base {
public :
int fun() { cout << "Base::fun() called" ; }
int fun( int i) { cout << "Base::fun(int i) called" ; }
};
class Derived : public Base {
public :
int fun() { cout << "Derived::fun() called" ; }
};
// Driver Code
int main()
{
Derived d;
d.fun(5); // Compiler Error
return 0;
}


输出

prog.cpp: In function ‘int main()’:
prog.cpp:20:12: error: no matching function for call to ‘Derived::fun(int)’
    d.fun(5); // Compiler Error
           ^
prog.cpp:13:9: note: candidate: int Derived::fun()
    int fun() { cout << "Derived::fun() called"; }
        ^
prog.cpp:13:9: note:   candidate expects 0 arguments, 1 provided

即使派生类方法的签名不同,基类中的所有重载方法都会隐藏。例如,在下面的程序中,派生::fun(char)使Base::fun()和Base::fun(int)都隐藏。

CPP

// CPP Program to demonstrate derived class redefines base
// class member method
#include <iostream>
using namespace std;
class Base {
public :
int fun() { cout << "Base::fun() called" ; }
int fun( int i) { cout << "Base::fun(int i) called" ; }
};
class Derived : public Base {
public :
// Makes Base::fun() and Base::fun(int )
// hidden
int fun( char c)
{
cout << "Derived::fun(char c) called" ;
}
};
// Driver Code
int main()
{
Derived d;
d.fun( 'e' ); // No Compiler Error
return 0;
}


输出

Derived::fun(char c) called

注: 以上事实对双方都适用 静止的 非静态 方法。

有一种方法可以缓解这种问题。如果我们想重载基类的函数,可以使用“using”关键字取消隐藏它。这个关键字带来了一个基类方法​或者将变量放入当前类的范围。

C++

// CPP Program to demonstrate derived class redefines base
// class member method using the 'using' keyword
#include <iostream>
using namespace std;
class Base {
public :
int fun() { cout << "Base::fun() called" ; }
};
class Derived : public Base {
public :
using Base::fun;
int fun( char c) // Makes Base::fun() and Base::fun(int )
// unhidden
{
cout << "Derived::fun(char c) called" ;
}
};
// Driver Code
int main()
{
Derived d;
d.fun(); // Works fine now
return 0;
}


输出

Base::fun() called

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享