重载超类的函数
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++。
Is there something in the C++ standard that prevents me from overloading a super class's function?
Starting with this pair of classes:
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
};
I can call B::foo()
easily:
B b;
b.foo (1, 2); // [1]
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)
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
};
And now I can call A::foo()
using the second example.
Is this standard? I'm using g++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在类
B
的定义中使用 using 声明:如果没有 using 声明,编译器在名称查找期间会找到
B::foo
并且实际上不会搜索基类对于具有相同名称的其他实体,因此找不到A::foo
。You need to use a using declaration inside the definition of class
B
: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, soA::foo
is not found.您没有重写
A::foo(int)
的实现,而是为A::foo
加上别名并将其签名更改为 (int,int) (int) 的。正如 James McNellis 提到的using A::foo;
声明使 A 中的函数可用。You're not overriding
A::foo(int)
's implementation, instead you're aliasingA::foo
and changing its signature to (int,int) instead of (int). As James McNellis mentioned theusing A::foo;
declaration makes the function from A available.