简体   繁体   English

将 class 成员 function 声明为模板 class 的朋友

[英]declaring a class member function as friend of a template class

#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;  
}       

The above program, when compiled, showed an error that y is neither a function nor a member function, so it cannot be declared a friend.上述程序在编译时显示错误, y既不是 function 也不是成员 function,因此不能声明为朋友。 What is the way to include getx as a friend in X ?getx作为朋友包含在X中的方法是什么?

You have to arrange the classes so that the function declared as a friend is actually visible before class X. You also have to make X visible before y...您必须安排课程,以便声明为朋友的 function 在 class X 之前实际上是可见的。您还必须在 y 之前使 X 可见...

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;}  
};      

You should "forward declare" class y before template class XIe, just put:您应该在模板 class XIe 之前“转发声明”class y,只需输入:

class y; class y; // forward declaration // 前向声明

template class X...模板 class X...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM