在 Visual C++ 2010 上运行此 C++ 源代码:
class B{
public:
virtual void f(int a){}
virtual void f(){}
};
class A:public B{
public:
virtual void f(int a){}
};
int main(){
A a;
a.f();
return 0;
}
导致以下错误:
IntelliSense:函数调用中的参数太少
也就是说,void f()
好像没有被继承?
问题是什么?
最佳答案
it seems that void f() didn't inherited?
A 类中的名称 f 阴影 B 中的名称 f。您仍然可以通过这种方式从 B 访问 foo()
A a;
a.B::f();
另一种选择是在 A 的范围内重新声明 B 的函数 foo:
class A : public B{
public:
virtual void f(int a) {}
using B::foo;
};
C++ 标准 n3337 § 10.2 成员名称查找
1) Member name lookup determines the meaning of a name (id-expression) in a class scope (3.3.7). Name lookup can result in an ambiguity, in which case the program is ill-formed. For an id-expression, name lookup begins in the class scope of this; for a qualified-id, name lookup begins in the scope of the nested- name-specifier. Name lookup takes place before access control (3.4, Clause 11).
2) The following steps define the result of name lookup for a member name f in a class scope C.
3) The lookup set for f in C, called S(f, C), consists of two component sets: the declaration set, a set of members named f; and the subobject set, a set of subobjects where declarations of these members (possibly including using-declarations) were found. In the declaration set, using-declarations are replaced by the members they designate, and type declarations (including injected-class-names) are replaced by the types they designate. S(f, C) is calculated as follows:
4) If C contains a declaration of the name f, the declaration set contains every declaration of f declared in C that satisfies the requirements of the language construct in which the lookup occurs. [ Note: Looking up a name in an elaborated-type-specifier (3.4.4) or base-specifier (Clause 10), for instance, ignores all non- type declarations, while looking up a name in a nested-name-specifier (3.4.3) ignores function, variable, and enumerator declarations. As another example, looking up a name in a using-declaration (7.3.3) includes the declaration of a class or enumeration that would ordinarily be hidden by another declaration of that name in the same scope. — end note ] If the resulting declaration set is not empty, the subobject set contains C itself, and calculation is complete.
5) Otherwise (i.e., C does not contain a declaration of f or the resulting declaration set is empty), S(f, C) is initially empty. If C has base classes, calculate the lookup set for f in each direct base class subobject Bi , and merge each such lookup set S(f, Bi ) in turn into S(f, C).
关于c++ - 无法识别的继承函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24351583/