c++:abiguos函数即使在每个继承级别都具有唯一的函数名称
代码 -
#include<iostream>
using namespace std;
class P {
public:
void print() { cout <<" Inside P"; }
};
class Q : public P {
public:
void print() { cout <<" Inside Q"; }
};
class Q2: public P {
public:
void print2() { cout <<" Inside Q2"; }
};
class R: public Q2, public Q { };
int main(void)
{
R r;
r.print(); // error: request for member ‘print’ is ambiguous
return 0;
}
预期行为:在MAIN中的第三行上没有模棱两可的呼叫。
实际行为:在Main 理由中的第三行上的模棱两可的呼叫
:我期望Q类隐藏P类P的print()函数P类。具有与R或Q(甚至P?)相同的函数名称。但是我故意将Q2中的函数名称更改为“ print2”,以避免此错误。当我将'q2'删除为父母类。
注意:我知道在隐藏的数据中,在多个类别继承的情况下,藏有类似的问题,但是这种情况是两种的混合物,我没有找到任何具体答案。
Code -
#include<iostream>
using namespace std;
class P {
public:
void print() { cout <<" Inside P"; }
};
class Q : public P {
public:
void print() { cout <<" Inside Q"; }
};
class Q2: public P {
public:
void print2() { cout <<" Inside Q2"; }
};
class R: public Q2, public Q { };
int main(void)
{
R r;
r.print(); // error: request for member ‘print’ is ambiguous
return 0;
}
Expected behavior: No ambiguous call on 3rd line in main.
Actual behavior: Ambiguous call on 3rd line in main
Rationale: I expected class Q to hide the print() function of class P. I would expect an ambiguous call error when Q2 has the same function name as R or Q (or even P?). But I deliberately changed the function name in Q2 to 'print2' to avoid this error. This error goes away when I remove 'Q2' as parent class of R. Is this happening because 'Q2' inherits 'print' from 'P'?
Note: I know similar questions have been asked on data hiding for regular inheritance and ambiguous calls in case of inheritance from multiple classes, but this case is sort of a mixture of two, and I did not find any specific answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这与
Q
隐藏超级类的print()
无关。Q2
从p
继承,因此继承print()
。print()
是从Q2和Q继承的。它们是相同的还是不同的方法是无关紧要的。关键是print()
方法r.print()
解决方案是模棱两可的。但确实如此。它继承了它。
This has nothing to do with
Q
hiding the superclass'sprint()
.Q2
inherits fromP
, and therefore inheritsprint()
.print()
is inherited from both Q2 and from Q. Whether they turn out to be the same or different methods is immaterial. The point is that it is ambigous whichprint()
methodR.print()
resolves to.But it does. It inherits it.
这是非常典型的c ++ 钻石问题具有多个遗传。
您所拥有的是当R调用打印功能时,他不知道从哪个打印到Cal。
您可以通过帮助R类对象指定要调用的打印来解决此问题。
以下修改可以说明这一点。
This is very typical C++ Diamond problem with multiple inheritance.
what you have is when R call the print functions he does not know from which print to cal.
you can solve this by helping the R class object to specify which print you want to call.
below modification can illustrate this.