10

C++ 标准中有什么东西阻止我重载超类的函数吗?

从这对类开始:

class A {            // super class
    int x;

public:
    void foo (int y) {x = y;}  // original definition
};

class B : public A { // derived class
    int x2;

public:
    void foo (int y, int z) {x2 = y + z;}  // overloaded
};

我可以B::foo()轻松调用:

    B b;
    b.foo (1, 2);  // [1]

但是,如果我尝试打电话A::foo()...

    B b;
    b.foo (12);    // [2]

...我得到一个编译器错误:

test.cpp: In function 'void bar()':
test.cpp:18: error: no matching function for call to 'B::foo(int)'
test.cpp:12: note: candidates are: void B::foo(int, int)

只是为了确保我没有遗漏任何东西,我更改了B's 函数的名称,以便没有重载:

class B : public A {
    int x2;

public:
    void stuff (int y, int z) {x2 = y + z;}  // unique name
};

现在我可以A::foo()使用第二个示例进行调用。

这是标准吗?我正在使用 g++。

4

2 回答 2

20

您需要在 class 的定义中使用 using 声明B

class B : public A {
public:
    using A::foo;          // allow A::foo to be found
    void foo(int, int);
    // etc.
};

如果没有 using 声明,编译器B::foo会在名称查找期间找到,并且实际上不会在基类中搜索具有相同名称的其他实体,因此A::foo找不到。

于 2011-01-04T18:31:41.937 回答
0

您没有覆盖A::foo(int)'s 的实现,而是使用别名A::foo并将其签名更改为 (int,int) 而不是 (int)。正如 James McNellis 所提到的,该using A::foo;声明使 A 中的函数可用。

于 2011-01-04T18:46:14.333 回答