我得了头痛感冒,可能是因为我太拥挤了而无法理解这里发生了什么,但我想不出以下内容为什么不能编译?
#include <string>
#include <iostream>
class Base {
public:
virtual void foo(const std::string & data) {
foo(data.data(), data.size());
}
virtual void foo(const void * bytes, int size) = 0;
};
class Derived : public Base{
public:
virtual void foo(const void * bytes, int size) {
std::cout << "Num Bytes: " << size << std::endl;
}
};
int main() {
Derived x;
std::string blah = "Hello";
x.foo(blah);
return 0;
}
我收到的错误信息是:
./foo.cpp: In function ‘int main()’:
./foo.cpp:25:15: error: no matching function for call to ‘Derived::foo(std::__cxx11::string&)’
x.foo(blah);
^
./foo.cpp:17:18: note: candidate: virtual void Derived::foo(const void*, int)
virtual void foo(const void * bytes, int size) {
^
./foo.cpp:17:18: note: candidate expects 2 arguments, 1 provided
如果我将第一个
foo
实例重命名为 fooString
,那么一切都正常了,所以似乎第二个 foo
实例在某种程度上隐藏了第一个实例。然而,考虑到第二个实例有两个参数而不是一个,我无法弄清它如何会产生歧义。更新:如果没有继承(如果它都是一个类),它也可以正常工作,所以我怀疑我误解了一些继承规则。
derived_object.base_class::function_name();
这将直接调用基类中的虚函数,而不管派生类中是否重载了该函数。 - user2100815x.Base::foo(blah);
- Jean-François Fabre