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 memb开发者_StackOverflow社区er function, so it cannot be declared a friend. What is the way to include getx
as a friend in 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...
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 X. I.e., just put:
class y; // forward declaration
template class X...
精彩评论