1

以下代码有什么问题?

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

2 回答 2

2

这是名称隐藏问题。根据名称查找规则,

(强调我的)

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

因此C::hash从基类中隐藏了名称。

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

struct C : public B {
  using B::hash;
  int hash(int x) const override {
    return x;
  }
};
于 2019-11-14T03:36:22.473 回答
1

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

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;
}
于 2019-11-14T03:35:45.753 回答