简体   繁体   English

C ++中的虚函数重写

[英]virtual function overriding in C++

I have a base class with virtual function - int Start(bool) In the derived there is a function with the same name but with a different signature - 我有一个带虚函数的基类 - int Start(bool)在派生中有一个具有相同名称但具有不同签名的函数 -

int Start(bool, MyType *)

But Not virtual 但不虚拟

In the derived Start() , I want to call the base class Start() 在派生的Start() ,我想调用基类Start()

int Derived::Start(bool b, MyType *mType)
{
    m_mType = mType;
    return Start(b);
}

But it gives compilation error. 但它给出了编译错误。

"Start' : function does not take 1 arguments"

However Base::Start(b) works 但是Base::Start(b)有效

In C#, the above code works ie the reference to Base is not required for resolving the call. 在C#中,上面的代码工作,即解析调用不需要对Base的引用。

Externally if the call is made as follows 如果呼叫如下进行,则在外部进行

Derived *d = new Derived();
bool b;
d->Start(b);

It fails with the message: 它失败并显示以下消息:

Start : function does not take 1 arguments

But in C#, the same scenaio works. 但在C#中,同样的情景也适用。

As I understand the virtual mechanism cannot be used for resolving the call, because the two functions have different signature. 据我所知,虚拟机制不能用于解析调用,因为这两个函数具有不同的签名。

But the calls are not getting resolved as expected. 但这些电话没有按预期得到解决。

Please help 请帮忙

Your two options are either add using Base::Start to resolve the scope of Start 你两个选择要么增加using Base::Start解决的范围Start

int Derived::Start(bool b, MyType *mType)
{
    using Base::Start;
    m_mType = mType;
    return Start(b);
}

Or as you noted add the Base:: prefix. 或者如您所述,添加Base::前缀。

int Derived::Start(bool b, MyType *mType)
{
    m_mType = mType;
    return Base::Start(b);
}

This is due to name hiding . 这是由于名称隐藏

When you declare a function in a derived class with the same name as one in the base class, the base class versions are hidden and inaccessible with an unqualified call. 当您在派生类中声明一个与基类中的函数同名的函数时,基类版本将被隐藏,并且无法通过非限定调用访问。

You have two options: either fully qualify your call like Base::Start(b) , or put a using declaration in your class: 您有两种选择:完全限定您的调用,如Base::Start(b) ,或在您的类中放置using声明:

using Base::Start;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM