会员功能没有继承?

时间:2016-06-28 18:19:37

标签: c++

这是我的代码

class B {
public:
  virtual void insert(int t, int p) = 0;

  void insert(int t) {
    insert(t, 0);
  }
};

class D : public B {
public:
  void insert(int t, int p) { }

};

int main() {
  D d;
  d.insert(1);
}

不会编译。当然,如果我在主要中说d.B :: insert(1),但为什么这不正确呢?感谢。

2 个答案:

答案 0 :(得分:9)

这是因为在这种情况下,基类功能不包含在重载决策中。类似的情况是在内部作用域中声明的函数 - 它们不会重载在外部作用域中声明的函数(参见下面的示例)。您可以想象派生类作用域嵌套在基类作用域内。

一旦编译器找到D::insert候选者,它将不会在基类中进一步查看。如果没有D::insert,则编译器将查看要调用的insert方法的基类。您可以通过从基类引入insert函数名来解决此问题:

using B::insert;

这将在派生类中引入所有B::insert重载函数。或者如您所说,您可以使用以下方法显式调用基类方法:

d.B::insert(1) 

过载如何在其他上下文中以相同方式工作的示例代码:

namespace Outer {
  void foo(double d) {
    std::cout << "Outer::foo(double d)\n";
  }
  namespace Inner {  
    //using Outer::foo; // uncomment to see "Outer::foo(double d)" in output
    void foo(int n) {
        std::cout << "Inner::foo(int n)\n";
    }
    void callMe() {
        foo(1.1);
    }
  }   
}

int main() {
    Outer::Inner::callMe(); // Outputes: Inner::foo(int n)
}

或:

void foo(std::string s) {
    std::cout << "foo(std::string s)\n";
}

void foo(double d) {
    std::cout << "foo(double d)\n";
}

void foo(int n) {
    std::cout << "foo(int n)\n";
}

int main() {
    void foo(int d); // comment out to see foo(double d) in output
    foo(1.1); // outputs: "foo(int n)", foo(double d) is hidden
    //foo("hello"); // ups, it wont compile - name lookup in c++ happens before type checking
                  // commenting out `void foo(int d);` above will fix this.
}

答案 1 :(得分:0)

我很确定这是因为你重新定义了D中的函数“insert”,这是被调用的函数。类“D”中的“插入”功能需要两个参数而不是一个。通过执行d.B :: insert(1),您在B中调用“insert”。