朋友功能模板类 [英] Friend function template class

查看:85
本文介绍了朋友功能模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有两种方法来处理模板类的朋友功能。

第一种方法是让朋友函数内联:

头文件啊

I know of two ways to deal with friend function of a template class.
The first way is make the friend function inline:
header file A.h




#ifndef A_H
#define A_H
#include<iostream>
using namespace std;
template <class T>
class A
{
	friend ostream& operator << (ostream& outs, const A<T>& object)
	{
		//definition goes here
	}
	//Other functions of class A
}
#endif //A_H






实施文件A.cpp


Implementation file A.cpp




//the rest of the function definition of class A






第二种方式是转发声明类A和友元函数然后你把友元函数定义和函数的其他定义实现文件中的A类

头文件啊


The second way is forward declare class A and the friend function and then you put the friend function definition and other definitions of functions of class A in implementation file
header file A.h




#ifndef A_H
#define A_H
#include<iostream>
using namespace std;
template <class T>
class A;
template <class T>
ostream& operator << (ostream& outs, const A<T>& object);
class A
{
	friend ostream& operator << <>(ostream& outs, const A<T>& object);
	//Other functions of class A
}
#endif //A_H






实施文件A.cpp


Implementation file A.cpp




#ifndef A.CPP
#define A.CPP
//the friend function definition and other function definitions
#endif //A.CPP






我不明白的是,在普通的类中,你总是可以在类定义之后定义友元函数。在模板类中,您必须在模板类中定义友元函数,或者转发声明友元函数。有没有解释呢?



我尝试过:



这是我所知道的两种方式。任何人都可以解释它们是如何工作的,如果有另一种方式?


What I dont understand is, in normal classes you can always define the friend functions after the classes definition. In template classes you either have to define friend function inside the template class or forward declare the friend function. Is there an explanation for this?

What I have tried:

These are the only two ways I know. Can anyone explain how they work and if there is another way?

推荐答案

原因是因为模板不是类定义,它是一个用于创建一个类定义。只有当你声明实际的类时,包括类型的声明( T ),编译器才会真正创建类定义。如果朋友声明在课堂之外,则无法保证该类型与课堂上声明的类型相匹配。
The reason is because the template is not a class definition, it is a template that is used to create a class definition. It is only when you declare the actual class, which includes the declaration of the type (T) does the compiler actually create the class definition. If the friend declaration is outside the class then there is no guarantee that the type will match what has been declared in the class.


这篇关于朋友功能模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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