c++函数调用
C++ function calling
我有个任务:
修复::
的错误调用,删除不可修复的结构
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)
。这是一个虚函数调用。由于p
是A*
类型的指针,编译器检查p->f()
是否对应a::f()的签名,并给参数赋默认值。编译器不知道指向对象属于哪个类。在运行时虚拟函数调用与所有参数定义"重定向"到实际实现,在你的情况下,这是A::f
参见
http://en.wikipedia.org/wiki/Diamond_problem相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销