C ++继承名称隐藏

时间:2014-05-07 20:59:03

标签: c++

我遇到了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) = %u\n", r->rnd2(16));
  delete r;
}

void barTest() {
  Bar* r = new Bar();
  printf("Bar->rnd2(16) = %u\n", 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) = %u\n", r->rnd(16));
  delete r;
}

void barTest() {
  Bar* r = new Bar();
  printf("Bar->rnd(16) = %u\n", 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) = %u\n", 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 ++不使用参数作为名称的一部分?它确实是这么多其他情况,为什么不呢?

1 个答案:

答案 0 :(得分:4)

如果你的意思是真的,请问它。添加声明

using Foo::rnd;

Bar的公开部分。

默认情况下,如果您使用某个名称提供方法,则会隐藏相同名称但签名不同的方法。这是因为当您打算覆盖时会出现这种情况,但是使用了错误的签名,如果发生这种情况,则很难检测到。

相关问题