重载超类的函数 [英] Overloading a super class's function

查看:128
本文介绍了重载超类的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there something in the C++ standard that prevents me from overloading a super class's function?

从这两个类开始:

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() easily:

I can call B::foo() easily:

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

但如果我尝试调用 A :: foo () ...

But if I try to call A::foo() ...

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

...我收到一个编译错误:

... I get a compiler error:

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 的函数的名称,以便没有重载:

Just to make sure I wasn't missing something, I changed the name of B's function so that there is no overload:

class B : public A {
    int x2;

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

现在我可以调用 A :: foo $ c>使用第二个例子。

And now I can call A::foo() using the second example.

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

Is this standard? I'm using g++.

推荐答案

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

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

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

Without the using declaration, the compiler finds B::foo during name lookup and effectively does not search base classes for other entities with the same name, so A::foo is not found.

这篇关于重载超类的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆