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的功能使得没有超载:

class B : public A {
    int x2;

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

现在我可以打电话 A::foo() 使用第二个示例。

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

有帮助吗?

解决方案

您需要在类的定义中使用使用声明 B:

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

没有使用声明,编译器会找到 B::foo 在名称查找过程中,有效地不会搜索具有相同名称的其他实体,因此 A::foo 找不到。

其他提示

你没有压倒一切 A::foo(int)实施,相反,您是在混音 A::foo 并将其签名更改为(int,int)而不是(int)。正如詹姆斯·麦克内利斯(James McNellis)提到的 using A::foo; 声明使该功能来自可用的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top