[英]Friend function scope and point of declaration
I've written the simple program: 我已经编写了简单的程序:
#include <stdio.h>
class A
{
friend void foo() { printf("asd\n"); }
};
int main()
{
A::foo();//fail, foo is not a member of A
}
How can I invoke this friend function defined inside the class body? 如何调用在类主体中定义的此朋友函数? Also I would like to know what is the point of declaration and scope of friend function. 我也想知道朋友功能的声明和作用范围是什么。
First of all to declare a friend function do 首先声明一个朋友函数
class A
{
friend void foo();
};
and define the function outside of the class 并在类之外定义函数
void foo { printf("asd\n"); }
It will be called as any other normal function 它将被称为任何其他正常函数
int main() {
foo();
}
The point is, that the friend
declaration in class A
allows foo()
access to any internal ( private
or protected
) members of this class. 关键是,类A
中的friend
声明允许foo()
访问此类的任何内部( private
或protected
)成员。
To additionally clarify: It is possible to define the function body at the point of the friend declaration, but it's still to be called as shown. 进一步说明一下:可以在friend声明的位置定义函数体,但是仍然需要如图所示进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.