首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为啥采用类模板形参类型的友元函数不能在该类中声明?

2013-07-09 
为什么采用类模板形参类型的友元函数不能在该类中声明???大家看一看,友元函数foo为什么不能在类模板C中声

为什么采用类模板形参类型的友元函数不能在该类中声明???
大家看一看,友元函数foo为什么不能在类模板C中声明,为什么使用自己的模板类型就可以声明了


#include <iostream>
using namespace std;
template <class T>
class C
{
private:
    T m[5];
public:
    friend void foo(const C<T>& t);  //使用类C的形参类型就不可以,为什么捏!
    //template <class U>             //定义自己的形参类型
    //friend void foo(const C<U>& t);//使用自己的形参类型,这样可以
};

template <class T>
void foo(const C<T>& t)
{
    for (int i = 0; i < 5; ++i)
    {
        cout << t.m[i] << endl;
    }
}
int main()
{
    C<int> c;
foo(c);
getchar();
return 0;


[解决办法]
C++标准规定: 想要限定对特定的实例化赋于友员关系, 必须在可以用于友元声明之前声明 类或函数.
只有当授于给定模板所有实例访问权的时候,可以不需要前置声明. 这也是你注释掉的部分为会么正确的原因.
以下可行.

template <class T>
class C;
template <class T>
void foo(const C<T>& t);
template <class T>
class C
{
private:
    T m[5];
public:
    friend void foo<T>(const C<T>& t);  //使用类C的形参类型就不可以,为什么捏!
};

template <class T>
void foo(const C<T>& t)
{
    for (int i = 0; i < 5; ++i)
    {
        cout << t.m[i] << endl;
    }
}
int main()
{
    C<int> c;
    foo(c);
    getchar();
    return 0;
}

热点排行