【问题标题】:Question about C++ call virtual function implemented in base from derived class关于派生类在基类中实现的C++调用虚函数的问题
【发布时间】:2019-11-14 03:31:38
【问题描述】:

以下代码有什么问题?

struct A {
  virtual int hash() const = 0;
  virtual int hash(int x) const = 0;
};

struct B : public A {
  int hash() const final {
    return 10;
  };

  int hash(int x) const override {
    return 10;
  };
};

struct C : public B {
  int hash(int x) const override {
    return x;
  }
};

#include <iostream>

int main() {
  C a;
  std::cout << a.hash() << std::endl;
  std::cout << a.hash(20) << std::endl;
  return 0;
}

我收到以下错误消息的编译错误

xx.cc:26:23: error: too few arguments to function call, single argument 'x' was
      not specified
  std::cout << a.hash() << std::endl;
               ~~~~~~ ^
xx.cc:17:3: note: 'hash' declared here
  int hash(int x) const override {
  ^
1 error generated.

【问题讨论】:

    标签: c++ inheritance member-functions name-lookup name-hiding


    【解决方案1】:

    这是名称隐藏问题。根据name lookup的规则,

    (强调我的)

    名称查找检查如下所述的范围,直到找到至少一个任何类型的声明,此时查找停止并且不再检查范围

    所以C::hash 对基类隐藏了名称。

    您可以申请using,将名称引入类C范围。

    struct C : public B {
      using B::hash;
      int hash(int x) const override {
        return x;
      }
    };
    

    【讨论】:

      【解决方案2】:

      是的,你必须在派生类中重新定义重载。

      struct C : public B {
        int hash(int x) const override {
          return x;
        }
        int hash() const override {
          return B::hash();
        }
      };
      

      或者通过对 B 的引用调用

      int main() {
        C a;
        B& b = a;
        std::cout << b.hash() << std::endl;
        std::cout << b.hash(20) << std::endl;
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 2019-07-16
        • 2018-10-21
        • 2011-09-08
        • 1970-01-01
        相关资源
        最近更新 更多