相关疑难解决方法(0)

访问在类中定义的友元函数

有这样的代码:

#include <iostream>

class A{

public:
    friend void fun(A a){std::cout << "Im here" << std::endl;}
    friend void fun2(){ std::cout << "Im here2" << std::endl; }
    friend void fun3();
};

void fun3(){
    std::cout << "Im here3" << std::endl;
}

int main() 
{  
    fun(A()); // works ok
    //fun2(); error: 'fun2' was not declared in this scope
    //A::fun2(); error: 'fun2' is not a member of 'A'
    fun3(); // works ok
} 
Run Code Online (Sandbox Code Playgroud)

如何访问fun2()函数?

c++ friend

41
推荐指数
2
解决办法
6677
查看次数

在struct中定义的调用友元函数需要前向声明吗?

在阅读Karlsson的超越C++标准时,作者在类reference_counted的主体中定义了朋友函数intrusive_ptr_add_ref(参见第36页).在适当的时间使用Argument Dependent Lookup自动调用该函数.

从来没有看过在类的主体中定义的友元函数,我玩过并发现如果不使用ADL查找,gcc 4.4.3需要前向声明.实际上,如果没有前向声明,似乎没有办法引用adl_no.这是C++标准的一部分还是gcc的神器?(我没有Windows框所以不能尝试VC).

#include <cstdlib>
#include <iostream>


namespace {
    void adl_no();        // Remove this and it won't compile with gcc

    struct Q {
        friend void adl_yes(const Q&) {
            std::cout << "adl_yes" << std::endl;
        }

        friend void adl_no() {
            std::cout << "adl_NO" << std::endl;
        }
    };
}


int main(int argc, char** argv)
{
    adl_yes(Q());
    adl_no();

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

c++ friend

5
推荐指数
1
解决办法
2748
查看次数

标签 统计

c++ ×2

friend ×2