c++继承名称隐藏

C++ inheritance name hiding

本文关键字:隐藏 继承 c++      更新时间:2023-10-16

我对c++和继承有一个问题。希望有人能给我解释一下。

编译并运行以下代码:

struct Foo {
  virtual ~Foo() {}
  virtual unsigned int rnd1() = 0;
  unsigned int rnd2(unsigned int limit) {
    return rnd1() % limit;
  }
};
struct Bar : public Foo {
  Bar() : state(12345678) {}
  unsigned int rnd1() {
    return state = state * 1664525 + 1013904223;
  }
 private:
  int state;
};
#include <cstdio>
void fooTest() {
  Foo* r = new Bar();
  printf("Foo->rnd2(16) = %un", r->rnd2(16));
  delete r;
}
void barTest() {
  Bar* r = new Bar();
  printf("Bar->rnd2(16) = %un", r->rnd2(16));
  delete r;
}
int main() {
  fooTest();
  barTest();
}

这里没有问题,因为rnd1rnd2有不同的名称。如果rnd1rnd2都重命名为rnd,它将不再编译。下面的代码无法编译:

struct Foo {
  virtual ~Foo() {}
  virtual unsigned int rnd() = 0;
  unsigned int rnd(unsigned int limit) {
    return rnd() % limit;
  }
};
struct Bar : public Foo {
  Bar() : state(12345678) {}
  unsigned int rnd() {
    return state = state * 1664525 + 1013904223;
  }
 private:
  int state;
};
#include <cstdio>
void fooTest() {
  Foo* r = new Bar();
  printf("Foo->rnd(16) = %un", r->rnd(16));
  delete r;
}
void barTest() {
  Bar* r = new Bar();
  printf("Bar->rnd(16) = %un", r->rnd(16));
  delete r;
}
int main() {
  fooTest();
  barTest();
}
下面是来自gcc的错误:
ubuntu:~$ g++ -Wall -Wextra -pedantic test.cpp 
test.cpp: In function ‘void barTest()’:
test.cpp:28:42: error: no matching function for call to ‘Bar::rnd(int)’
    printf("Bar->rnd(16) = %un", r->rnd(16));
                                      ^
test.cpp:28:42: note: candidate is:
test.cpp:11:16: note: virtual unsigned int Bar::rnd()
    unsigned int rnd() {
            ^
test.cpp:11:16: note:   candidate expects 0 arguments, 1 provided

我的问题是:为什么c++不使用参数作为名称的一部分?在很多其他情况下都是这样,为什么现在不行呢?

如果你是真心的,请问一下。添加声明

using Foo::rnd;

Bar的公共部分。

默认情况下,如果您以某些名称提供方法,则隐藏相同名称但不同签名的方法。这是因为当您打算重写但使用了不正确的签名时,通常会错误地发生这种情况,并且如果发生这种情况,将很难检测到。