将类成员函数声明为模板类的友元函数

3
#include< iostream>  
using namespace std;  

template< class t>  
class X  
{  
  private:  
      t x;    

  public:  
        template< class u>  
         friend u y::getx(X< u> ); 

      void setx(t s)  
      {x=s;}  
           };      

class y   
{  
 public:  
     template< class t>  
     t getx(X< t> d)  
     {return d.x;}     
};  

int main()  
{  
    X< int> x1;  
    x1.setx(7);  
    y y1;  
    cout<< y1.getx(x1);    
    return 0;  
}       

上述程序编译时显示错误,提示 y 不是函数或成员函数,因此不能被声明为友元。如何在 X 中将 getx 声明为友元呢?

2个回答

2

你需要安排类的顺序,确保声明为友元的函数在 X 类之前可见。你还需要确保 X 类在 y 类之前可见...

template< class t>  
class X;

class y   
{  
 public:  
     template< class t>  
     t getx(X< t> d)  
     {return d.x;}     
};

template< class t>  
class X  
{  
  private:  
      t x;    

  public:  
        template< class u>  
         friend u y::getx(X< u> ); 

      void setx(t s)  
      {x=s;}  
};      

但是我已经在类y之前定义了整个类x...是否需要前向声明...它有什么作用? - AvinashK
@avinash - 要使一个函数成为友元函数,该函数必须是可见的,这意味着类y必须是可见的,因为该函数是一个成员。在声明该成员函数时,类X也必须是可见的,因为它是一个参数。前向声明表示X是一个类模板,在那一点上已经足够了。 - Bo Persson

1
在模板类X之前,您应该“前置声明”类y。例如,只需加入:
class y; // 前置声明
template class X...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接