C++ function calling [closed]
I have a task:
Fix wrong calls with ::
, delete unfixable constructions
int x = 4;
class A{
int x;
public:
A(int n = 1);
virtual int f(int a=0, int b=0);
};
class B{
int x;
public:
B(int n = 2);
int f(int a = 0);
};
class C: public A, public B{
int x;
public:
C(int n=3);
int f(int a, int b=0);
int g(A *p);
};
A * p; C c;
int main (int argc, char const *argv[])
{
p = &c;
x = c.g(p);
x = c.f(); // wrong , no candidate , x=c.B::f()
x = c.f(x);// C::f(int,int)
x = c.f(x,1);// C::f(int,int)
x = p->f();// C::f(int,int)
x= p->f(x);// C::f(int,int)
x = p->f(x,1); // C::f(int, int)
return 0;
}
Can you explain these situations:
x = c.f(); // wrong , no candidate , x=c.B::f()
x = c.f(x);// C::f(int,int)
x = p->f();// C::f(int,int)
开发者_Go百科Where can I find function selection algorithm?
Overload resolution is not applied across different class scopes (§7.4). In particular, ambiguities between functions from different base classes are not resolved based on argument types.
(Stroustrup, The C++ Programming Language, 15.2.2)
Thus, compiler searches method by name first in "this" class, then recoursively in base classes regardless of wheather default values exist
x = c.f(); // wrong arguments number for C::f
x = c.f(x);// C::f(int,int) // it's clear
As of the last case x = p->f();// C::f(int,int)
. It's a virtual function call. since p
is a pointer of type A*
, compiler check if p->f()
corresponds to signature of A::f() and assigns default values to parameters. Compiler doesn't know which class the pointed object belongs to. At runtime virtual function call with all arguments defined "redirected" to actual implementation, in your case this is A::f
See
http://en.wikipedia.org/wiki/Diamond_problem
for the resolution.
精彩评论