关于友元函数在类内定义的问题

我们平常使用友元函数都仅是在类内部声明,在类外定义,今天看到了一个在类内定义的例子,就产生了好奇,把自己的总结记录下来;

先看例子 

class T 
{
	public:
		T();
		~T();

		//不引入类对象
		friend void show_hello_no_param()
		{
			std::cout << "show_hello_no_param() of T : Hello world!\n";
		}

		//引入类对象
		friend void show_hello(T t)
		{
			std::cout << "show_hello() of T : Hello world!\n";
		}

};

int main(int argc, char* argv[])
{
	T t;

	show_hello_no_param();      //编译不通过

	show_hello(t);              //编译可以通过

	getchar();

	return 0;
}

根据上面的例子感觉像是类内定义的友元函数在类对象的作用域内可以编译通过;

同时也试了下传指针也能编译通过,T* t=NULL或 t = new T()结果一样都能通过;

T* t=NULL;//new T();

//show_hello_no_param();      //编译不通过

show_hello(t);              //编译可以通过

这里面到底涉及什么原理还没搞清楚,希望清楚的高手能赐教一下。

另外 

#include<iostream>
using namespace std;

class Au
{ 
private:
	int a; 
	int b;
	int c;
	//inline friend void fun();
	public:
	friend void funA(Au a) 
	{ 
		cout << a.a << "funA" << endl; 
	} 
	
	friend void funB() 
	{ 
		cout << b << "funB" << endl;    //编译报错 成员b不是静态static的
	} 
	
	friend void funC() 
	{ 
		cout << "funC" << endl; 
	} 
};

int main()
{
	Au a; 
	funA(a); 
	funB();        //编译报错:函数未定义,同上个例子(将改为static的之后仍然报这个错)
	funC();        //编译报错:说函数未定义,同上个例子

	return 0; 
}

编译如下: 

yu@MAC:~/$ g++ qq.cpp -o main -Wall
qq.cpp: In function ‘int main()’:
qq.cpp:39:2: error: ‘funB’ was not declared in this scope
  funB();
  ^~~~
qq.cpp:40:2: error: ‘funC’ was not declared in this scope
  funC();

参考:

       关于友元函数在类内定义的问题--笔记 - 郭流水 - 博客园 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值