VS2008 C++ can't seem to inherit const overloa

2019-07-31 19:11发布

问题:

This question already has an answer here:

  • Derived class not inheriting overloaded method from base class 2 answers

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);
}

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).

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.

What the hell? Am I missing something?

回答1:

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

no matching function for call to ‘Child::doIt(const int&)’ sc.doIt(c_i);

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.

You should provide both overrides:

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);}
};

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;
};