无法使用基类的方法

Unable to use method of base class

本文关键字:方法 基类      更新时间:2023-10-16

可能重复:
重载函数隐藏在派生类中

似乎我不能直接在派生类中使用基类中的方法,如果它们在C++中的基类和派生类中都重载了。以下代码产生错误no matching function for call to ‘Derived::getTwo()’

class Base {
public:
    int getTwo() {
        return 2;
    }
    int getTwo(int, int) {
        return 2;
    }
};
class Derived : public Base {
public:
    int getValue() {
        // no matching function for call to ‘Derived::getTwo()’
        return getTwo();
    }
    int getTwo(int) {
        return 2;
    }
};

如果我将return getTwo();更改为return ((Base*) this)->getTwo(),它是有效的,但对我来说这看起来很难看。我该如何解决这个问题?

附言:如果这很重要的话,我使用g++4.7和std=gnu++c11选项。

任一:

class Derived : public Base {
public:
    using Base::getTwo; // Add this line
    int getValue() {
        // no matching function for call to ‘Derived::getTwo()’
        return getTwo();
    }
    int getTwo(int) {
        return 2;
    }
}

        return Base::getTwo();

这就是C++中名称查找的工作方式:

namespace N1
{
    int getTwo();
    int getTwo(int, int);
    namespace N2
    {
        int getTwo(int);
        namespace N3
        {
            call getTwo(something char*);
        }
    }
}

当前上下文为N3。该层上没有getTwo。好的,去上层。N2包含CCD_ 5的一个定义。编译器将尝试使用此定义,并且不会搜索上层上下文。来自N2的getTwo隐藏了所有上层上的getTwo的所有定义。有时这会导致重载方法的混乱。

如果添加using Base::getTwo;,实际上就是向内部上下文添加了一个定义代理。上部上下文temsellves的定义不可见。但是代理是可见的。