首页 > 解决方案 > 错误:未在此范围内声明友元函数

问题描述

/****************对.h******************/

 #include<iostream>
    using namespace std;
    template<class T1,class T2>
    class Pair
    {
    private :
      T1 first;
      T2 second;
    public  :
      Pair(T1,T2);
      Pair(){};
      Pair<T1,T2>  make(T1  a , T2  b);
      void operator=(const Pair& other);
      friend ostream& operator<<(ostream& out ,const Pair<T1,T2>& A);

    };

/*******************main.cpp************************/

#include<iostream>
#include<utility>
#include"Pair.h"
using namespace std;

int main()
 {
  Pair<int,int> A=make(10,20);
 cout << A ;
  return 0;
}

/*************************对.cpp******************/

#include"Pair.h"
 #include<ostream>
 using namespace std;

template<class T1, class T2>
 Pair<T1,T2>::Pair(T1 a,T2 b){
   this->first = a;
   this->second = b;
 }

 template<class T1, class T2>
void  Pair<T1,T2>::operator=(const Pair& other)
 {
    this->first = other.first;
    this->second = other.second;
 }

 template<class T1, class T2>
ostream& operator<<(ostream& out ,const Pair<T1,T2> A)
{
  out<<"("<<A.first<<" , "<<A.second<<")";
  return out;
}

 template<class T1, class T2>
 Pair<T1,T2> make(T1   a , T2   b)
{
  return (Pair<T1,T2> (a,b)) ;
    }

它给了我函数 make 的错误;因为它没有在 main 范围内声明,我不明白为什么。所有友元函数和模板也存在问题。该程序不想被编译。

标签: c++

解决方案


make是一个全局函数。你的头文件应该是这样的

template<class T1,class T2>
class Pair
{
private :
  T1 first;
  T2 second;
public  :
  Pair(T1,T2);
  Pair(){};
  void operator=(const Pair& other);
  friend ostream& operator<<(ostream& out ,const Pair<T1,T2>& A);

};

template<class T1,class T2>
Pair<T1,T2>  make(T1  a , T2  b);

另外,您的代码还有其他问题。一方面,您的所有代码都应该在头文件中,正如上面评论中的链接问题中所解释的那样。

另请参阅此问题以了解模板朋友问题

为模板类重载友元运算符 <<


推荐阅读