【问题标题】:Unable to use method of base class [duplicate]无法使用基类的方法[重复]
【发布时间】:2012-07-14 00:22:46
【问题描述】:

可能重复:
overloaded functions are hidden in derived class

如果在 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(),它可以工作,但对我来说这看起来很难看。我该如何解决这个问题?

附:如果这很重要,我会使用带有选项 std=gnu++c11 的 g++ 4.7。

【问题讨论】:

  • 这肯定会作为副本关闭,但与此同时,快速的答案是将using Base::getTwo 添加到您在类范围内的Derived 定义中。

标签: c++ class inheritance methods


【解决方案1】:

要么:

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

【讨论】:

  • 谢谢!你能解释一下为什么这也有效吗?或者更确切地说,为什么它不会?
  • @RPFeltz:叫做hiding,基本上这个过程就是lookup在最近的上下文中开始(在getValue()方法+ADL里面开始)并试图找到@ 987654324@,如果没有找到,则检查下一个作用域,以此类推。一旦它在一个上下文中找到标识符,它就会停止搜索。在您的情况下,它会在您的类中找到 int getTwo(int),因此它不会查看基类中的其他重载。两种替代解决方案是:使用using base::getTwo; 将基重载带入派生类范围,以便在类中可用...
  • ... 然后重载解析将选择最合适的重载。另一种解决方案是使用base::getTwo() 限定调用,这将告诉编译器您希望从基类上下文中获得getTwo()(即避免在当前范围内开始查找并在base 内跳转搜索getTwo
【解决方案2】:

这就是 C++ 中名称查找的工作原理:

namespace N1
{
    int getTwo();
    int getTwo(int, int);

    namespace N2
    {
        int getTwo(int);

        namespace N3
        {
            call getTwo(something char*);
        }
    }
}

当前上下文是 N3。这一层没有getTwo。好,上一层。 N2 包含getTwo 的一个定义。编译器会尝试使用这个定义并且不会搜索上层上下文。 N2 中的getTwo 隐藏了所有上层getTwo 的所有定义。有时这会导致与重载方法混淆。

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

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多