定义在类中的友元函数

#include "stdafx.h"
#include<iostream>


using std::cout;
using std::endl;

class X{
public:
X(int t=10):val(t){}

//friend void fun(const X &);//声明
friend void fun(const X &orj){cout<<orj.val<<endl;};
friend class Y;
private:
int val;
};

//void fun(const X &orj){cout<<orj.val<<endl;};//定义
int main()
{

X x;
fun(x);

system("pause");
return 0;

}

定义在类中的友元函数,其作用域在全局作用域下.

如果没有在类中的友元声明之前声明的友元函数,其作用域则在第一个包围类的非类作用域下.

以下来自MSDN的解释.

A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and –>) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

If you declare a friend function that was not previously declared, that function is exported to the enclosing nonclass scope.

Friend functions can be defined inside class declarations. These functions are inline functions, and like member inline functions they behave as though they were defined immediately after all class members have been seen but before the class scope is closed (the end of the class declaration).

Friend functions defined inside class declarations are not considered in the scope of the enclosing class; they are in file scope.

 

从从红字部分知道,定义在类内部的友元函数,也是内联函数,而且是在所有成员定义之后被定义.

展开阅读全文

没有更多推荐了,返回首页