在类中定义的访问friend函数 [英] Access friend function defined in class

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

问题描述

有这样的代码:

#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
} 

如何访问函数fun2()?

How to access function fun2()?

推荐答案

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();
};

虽然你的定义 fun2 c c 定义一个全局函数而不是成员,并使它成为 A 同时,你仍然缺少一个在全局范围本身的相同的函数的声明。

Although your definition of fun2 does define a "global" function rather than a member, and makes it a friend of A at the same time, you are still missing a declaration of the same function in the global scope itself.

这意味着没有在那个范围的代码有任何想法 fun2 存在。

That means that no code in that scope has any idea that fun2 exists.

fun 参数依赖查找可以接管并查找函数,因为有一个类型 A

The same problem occurs for fun, except that Argument-Dependent Lookup can take over and find the function, because there is an argument of type A.

I建议使用通常的方式定义您的函数:

I recommend instead defining your functions in the usual manner:

class A {
   friend void fun(A a);
   friend void fun2();
   friend void fun3();
};

void fun(A a) { std::cout << "I'm here"  << std::endl; }
void fun2()   { std::cout << "I'm here2" << std::endl; }
void fun3();

请注意, 一切工作 fun3 除外,因为我从未定义它)。

Notice now that everything works (except fun3 because I never defined it).

这篇关于在类中定义的访问friend函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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