类函数隐藏的C ++朋友函数? [英] C++ friend function hidden by class function?

查看:98
本文介绍了类函数隐藏的C ++朋友函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最小范例:

class A
{
    friend void swap(A& first, A& second) {}
    void swap(A& other) {}
    void call_swap(A& other)
    {
        swap(*this, other);
    }
};

int main() { return 0; }

g ++ 4.7说:

g++ 4.7 says:

friend.cpp: In member function ‘void A::call_swap(A&)’:
friend.cpp:7:20: error: no matching function for call to ‘A::swap(A&, A&)’
friend.cpp:7:20: note: candidate is:
friend.cpp:4:7: note: void A::swap(A&)
friend.cpp:4:7: note:   candidate expects 1 argument, 2 provided

取消注释第4行:

// void swap(A& other) {}

...它工作正常。

...and it works fine. Why, and how to fix this, if I want to keep both variants of my swap function?

推荐答案

我相信这是因为它是为什么,以及如何解决这个问题,如果我想保留我的交换函数的两个变体?编译器试图在类中找到该函数。这应该是一个简单的更改,使其工作(它在Visual Studio 2012中工作):

I believe it is because the compiler is trying to find the function within the class. This should be a minimalistic change to make it work (it works in Visual Studio 2012):

class A; // this and the next line are not needed in VS2012, but
void swap(A& first, A& second); // will make the code compile in g++ and clang++

class A
{
    friend void swap(A& first, A& second) {}
    void swap(A& other) {}
    void call_swap(A& other)
    {
        ::swap(*this, other); // note the scope operator
    }
};

int main() { return 0; }

这篇关于类函数隐藏的C ++朋友函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆