简体   繁体   English

有关朋友功能的问题

[英]A question about friend functions

I faced a problem recently with a 3rd party library which generates classes from a xml. 我最近遇到了一个第三方库,该库从xml生成类。 Here is a gist of it: 这是要点:

class B;
class A
{
    void doSomething();
    friend class B; 
};

class B
{
    void doSomething();
    void doSomethingMore()
    {
        doSomething();
    }
};

The compiler flags call to the function doSomething() as ambiguous and flags it as an compiler error. 编译器将对doSomething()函数的调用标记为模棱两可,并将其标记为编译器错误。 It is easy to understand why it gives the error. 很容易理解为什么会给出错误。 Class B being friend of class A , every member of class B has access to all the members of class A . Class B的存在的朋友class A ,的每一个成员class B访问的所有成员class A Renaming of the either of functions resolved my problem but it got me thinking that shouldn't in this case the compiler should give a priority to the class's own member function over the function in another class of which it is a friend? 重命名这两个函数可以解决我的问题,但是让我想到,在这种情况下,编译器不应该将其自身的成员函数赋予优先于其另一个朋友的函数的优先级吗?

Note: I will update the compiler version details tomorrow..Need to check the exact version details at the workplace. 注意:明天我将更新编译器的版本详细信息。需要在工作场所检查确切的版本详细信息。 I guess i should have got them in first place..:( 我想我应该把它们放在首位.. :(

[Problem Update & Resolution] [问题更新与解决]
I checked out again with a small sample program and my bad the problem is not with the ambiguity due to friend functions. 我用一个小的示例程序再次签出,但是我的问题不是由于朋友功能引起的歧义。 The 3rd party library internally generates a function with the same signature and inside the same class which causes the ambiguity. 第三方库在内部生成具有相同签名且在同一类内部的函数,从而导致歧义。 Thanks for the replies, at least my misconception got corrected :) 感谢您的答复,至少我的误解得到了纠正:)

There is no ambiguity. 没有歧义。 The function called in A requires an A instance. 在A中调用的函数需要一个A实例。 The function called in B requires a B instance. 在B中调用的函数需要一个B实例。

doSomethingMore is called on a B instance and therefore the function that gets called is the one in B. 在B实例上调用doSomethingMore,因此被调用的函数是B中的一个。

You seem to have misunderstood friendship. 您似乎对友谊有误解。 All it means is that, in this case, given an instance of A, member functions of B can call the A::doSomething() function or do anything else in A that has private access. 这意味着在这种情况下,给定A的实例,B的成员函数可以调用A :: doSomething()函数或在A中执行任何具有私有访问权限的操作。

There's absolutely no ambiguity in your example. 您的示例中绝对没有歧义。 Making one class friend of another has no such effect on the name lookup as you describe. 像您描述的那样,使一个类的朋友成为另一类的朋友对名称查找没有任何影响。 The "It is easy to understand..." explanation does not really make much sense from the language point of view. 从语言的角度来看,“易于理解...”的解释并没有多大意义。

While it is possible that a broken compiler might behave the way you describe, most likely you missed something and the reason for the ambiguity is different. 尽管损坏的编译器可能会按照您的描述进行操作,但很可能您错过了某些内容,并且产生歧义的原因有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM