定义在类中的友元函数

34 篇文章 0 订阅

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

 

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值