Function with same name but different signature in derived class(派生类中具有相同名称但不同签名的函数)
问题描述
我有一个同名的函数,但在基类和派生类中具有不同的签名.当我尝试在从派生继承的另一个类中使用基类的函数时,我收到一个错误.见以下代码:
I have a function with the same name, but with different signature in a base and derived classes. When I am trying to use the base class's function in another class that inherits from the derived, I receive an error. See the following code:
class A
{
public:
void foo(string s){};
};
class B : public A
{
public:
int foo(int i){};
};
class C : public B
{
public:
void bar()
{
string s;
foo(s);
}
};
我从 gcc 编译器收到以下错误:
I receive the following error from the gcc compiler:
In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int)
如果我从类 B
中删除 int foo(int i){};
,或者如果我从 foo1
重命名它,一切正常美好的.
If I remove int foo(int i){};
from class B
, or if I rename it from foo1
, everything works fine.
这有什么问题?
推荐答案
派生类中的函数不覆盖基类中的函数但具有相同名称的函数将隐藏相同的其他函数基类中的名称.
Functions in derived classes which don't override functions in base classes but which have the same name will hide other functions of the same name in the base class.
通常认为在派生类中具有与基类中的函数同名的函数是不好的做法,这些函数并不打算覆盖基类函数,因为您所看到的通常不是可取的行为.通常最好给不同的函数起不同的名字.
It is generally considered bad practice to have have functions in derived classes which have the same name as functions in the bass class which aren't intended to override the base class functions as what you are seeing is not usually desirable behaviour. It is usually preferable to give different functions different names.
如果您需要调用基本函数,则需要使用 A::foo(s)
来限定调用范围.请注意,这也会同时禁用 A::foo(string)
的任何虚函数机制.
If you need to call the base function you will need to scope the call by using A::foo(s)
. Note that this would also disable any virtual function mechanism for A::foo(string)
at the same time.
这篇关于派生类中具有相同名称但不同签名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:派生类中具有相同名称但不同签名的函数


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09