在派生类中具有相同名称但不同签名的函数 [英] Function with same name but different signature in derived class

查看:200
本文介绍了在派生类中具有相同名称但不同签名的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相同名称的函数,但在基础和派生类中有不同的签名。当我试图使用基类的函数在另一个类继承从派生,我收到一个错误。请参阅以下代码:

 类A 
{
public:
void foo s){};
};

class B:public A
{
public:
int foo(int i){};
};

class C:public B
{
public:
void bar()
{
string s;
foo(s);
}
};

我从gcc编译器收到以下错误:


$ b $在成员函数`void C :: bar()':没有匹配的函数调用`C :: foo(std :: string&)'候选人是:int B :: foo(int)



如果我删除 int foo {code>,> ,精细。



这有什么问题?

解决方案

派生类中的函数它不覆盖基类中的函数,但是具有相同的名称将会隐藏基类中相同名称的其他函数。



通常认为不好的做法是在派生类中具有与bass类中的函数同名的函数,这些函数不会覆盖基类函数,因为您所看到的通常不是所期望的行为。通常最好给不同的函数不同的名字。



如果你需要调用基函数,你需要使用 A :: foo(s)。注意,这也将同时禁用 A :: foo(string)的任何虚拟函数机制。


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?

解决方案

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 for A::foo(string) at the same time.

这篇关于在派生类中具有相同名称但不同签名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆