未找到派生类中具有相同名称但不同签名的函数
我有一个具有相同名称的函数,但在基类和派生类中具有不同的签名。 当我尝试在从派生类继承的另一个类中使用基类的函数时,我收到错误。 请参阅以下代码:
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 编译器收到以下错误:
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 开始,一切正常。
这有什么问题吗?
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);
}
};
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)
If I remove int foo(int i){};
from class B
, or if I rename it from foo1
, everything works fine.
What's the problem with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为如果在您的基地之一找到名称,名称查找就会停止。 它不会把目光投向其他基地。 B 中的函数隐藏 A 中的函数。您必须在 B 的范围内重新声明 A 的函数,以便这两个函数在 B 和 C 中都可见:
编辑:真实描述标准给出的是(来自 10.2/2):
它在另一个地方(就在它的上方)有以下内容:
([...]由我放置)。 请注意,这意味着即使 B 中的 foo 是私有的,A 中的 foo 仍然找不到(因为访问控制稍后发生)。
It is because name lookup stops if it finds a name in one of your bases. It won't look beyond in other bases. The function in B shadows the function in A. You have to re-declare the function of A in the scope of B, so that both functions are visible from within B and C:
Edit: The real description the Standard gives is (from 10.2/2):
It has the following to say in another place (just above it):
([...] put by me). Note that means that even if your foo in B is private, the foo in A will still not be found (because access control happens later).
派生类中的函数如果不重写基类中的函数但具有相同的名称,则会隐藏基类中的其他同名函数。
通常认为派生类中的函数与低音类中的函数同名是不好的做法,而派生类中的函数并不打算覆盖基类函数,因为您所看到的通常不是理想的行为。 通常最好为不同的函数指定不同的名称。
如果您需要调用基函数,则需要使用
A::foo(s)
来确定调用范围。 请注意,这也会同时禁用A::foo(string)
的任何虚拟函数机制。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.
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 forA::foo(string)
at the same time.