VS2008 C ++似乎不能继承const重载方法 [英] VS2008 C++ can't seem to inherit const overloaded method

查看:186
本文介绍了VS2008 C ++似乎不能继承const重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是惊讶地发现以下不编译VS2008。
编译器声明它不能将参数1从const int转换为int&因此证明它没有在Base类中查看可用的方法。

I was just surprised to find that the following does not compile in VS2008. The compiler complains that it cannot convert parameter 1 from const int to int& thus demonstrating that it is failing to look at the available method in the Base class.

有没有很好的理由,或者是其他编译器中没有的缺陷?

Is there a good reason for this or is it a deficiency not found in other compilers?

struct Base
{
    virtual void doIt(int& v){cout << "Base NonConst v=" << v << endl;}
    virtual void doIt(const int& v) const {cout << "Base Const v=" << v << endl;}
};

struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}    
};

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 99;
    const int& c_i = i;

    Child sc;
    sc.doIt(i);
    sc.doIt(c_i);
}

如果我删除了子项中的单个重写方法,类或者如果我通过Base指针访问子类(或者当然如果我在子类中覆盖了两个方法)。

This compiles and works as expected if I remove the single overridden method in the Child class or if I access the child class through a Base pointer (or of course if I override both methods in the child class).

然而,当直接从Child类或Child类指针访问时,覆盖一个而不是另一个方法似乎隐藏未覆盖的Base类方法。

However overriding one and not the other method seems to hide the un-overridden Base class method when accessing directly from the Child class or a Child class pointer.

到底是什么?

推荐答案

您收到的错误将发生在每个编译器(包括gcc,msvc 2013等) )

This error you are receiving will happen in every compiler (including gcc, msvc 2013, etc..)

没有匹配函数调用'Child :: doIt(const int&)'sc.doIt(c_i);

这是问题。您将覆盖函数 doIt ,并且只有当父类有两个时才提供一个覆盖。它不会搜索父类,因为你正在覆盖它。

That is the problem. You are overriding the function doIt and only providing one override when the parent class has two. It won't search the parent class since you are overriding it.

您应该同时提供覆盖:

struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}    
    virtual void doIt(const int& v) const { Base::doIt(v);}
};

也可以使用语句像这样(C ++ 11):

OR you can also do a using statement like so (C++11):

struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}  

    using Base::doIt;
};

这篇关于VS2008 C ++似乎不能继承const重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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