问题描述
我知道有两种方法来处理模板类的朋友功能。
第一种方法是让朋友函数内联:
头文件啊
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?
推荐答案
这篇关于朋友功能模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!