【问题标题】:virtual function overriding in C++C++中的虚函数覆盖
【发布时间】:2015-06-12 14:02:11
【问题描述】:

我有一个带有虚函数的基类 - int Start(bool) 在派生中有一个名称相同但签名不同的函数 -

int Start(bool, MyType *)

但不是虚拟的

在派生的Start()中,我想调用基类Start()

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

但它给出了编译错误。

"Start' : function does not take 1 arguments"

但是Base::Start(b) 有效

在 C# 中,上述代码有效,即解析调用不需要对 Base 的引用。

外部如果调用如下

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

失败并显示消息:

Start : function does not take 1 arguments

但在 C# 中,同样的场景也适用。

据我了解,虚拟机制不能用于解析调用,因为这两个函数具有不同的签名。

但呼叫没有按预期得到解决。

请帮忙

【问题讨论】:

标签: c# c++ oop


【解决方案1】:

您的两个选项是添加using Base::Start 来解析Start 的范围

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

或者如您所述,添加 Base:: 前缀。

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

【讨论】:

  • 请注意 Base 在嵌套的命名空间内。所以我给了 - A::B::C::Base::Start 。使用 using 选项,IDE 中会显示以下错误 - “不允许使用类限定名称”。
【解决方案2】:

这是由于名称隐藏

当您在派生类中声明与基类中同名的函数时,基类版本将被隐藏且无法通过非限定调用访问。

您有两个选择:要么完全限定您的调用,例如 Base::Start(b),要么在您的类中声明 using

using Base::Start;

【讨论】:

  • 当调用来自派生类成员函数时,使用完全限定名称看起来没问题。但是对于从派生类对象调用 Base::Start(),使用 using 指令的第二种方法看起来更好。但这给出了错误-“不允许使用完全限定的名称”
猜你喜欢
  • 2015-06-17
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 2020-12-16
  • 2013-10-04
  • 2010-10-04
  • 1970-01-01
相关资源
最近更新 更多