开发者

C++ function calling [closed]

开发者 https://www.devze.com 2023-02-23 13:44 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消