c++函数调用

C++ function calling

本文关键字:函数调用 c++      更新时间:2023-10-16

我有个任务:

修复::的错误调用,删除不可修复的结构

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;
}

你能解释一下这些情况吗?

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)

我在哪里可以找到函数选择算法?

重载解析不应用于不同的类作用域(§7.4)。特别是歧义来自不同基类的函数之间不能根据参数类型进行解析。

(Stroustrup, c++编程语言,15.2.2)

因此,编译器首先在"this"类中按名称搜索方法,然后在基类中递归地搜索方法,而不管默认值是否存在

x = c.f(); // wrong arguments number for C::f
x = c.f(x);// C::f(int,int) // it's clear

最后一种情况x = p->f();// C::f(int,int)。这是一个虚函数调用。由于pA*类型的指针,编译器检查p->f()是否对应a::f()的签名,并给参数赋默认值。编译器不知道指向对象属于哪个类。在运行时虚拟函数调用与所有参数定义"重定向"到实际实现,在你的情况下,这是A::f

参见

http://en.wikipedia.org/wiki/Diamond_problem