开发者

A question about friend functions

开发者 https://www.devze.com 2023-02-12 04:02 出处:网络
I faced a problem recently with a 3rd party library which generates classes from a xml. Here is a gist of it:

I faced a problem recently with a 3rd party library which generates classes from a 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. 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. 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 checke开发者_JS百科d 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. The function called in B requires a B instance.

doSomethingMore is called on a B instance and therefore the function that gets called is the one in 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.


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.

0

精彩评论

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