////////////////////////////////////////////////
//源代码如下:
////////////////////////////////////////////////
#include <iostream.h>
#include <tchar.h>//类声明
class MyClass
{
private:
int i, j;public:
MyClass() : i(10), j(20) {}
template <typename T>
friend int Add(T t1, T t2);
};//模板函数声明
template <typename T>
int Add(T t1, T t2)
{
return t1.i + t2.j;
}//主函数
void _tmain()
{
MyClass t1, t2;
int t = Add<MyClass>(t1, t2);
cout << t;
}问题:为什么把模板函数的声明放在类声明的前面不行?
希望大家帮帮我。我的理念:共同进步。

解决方案 »

  1.   

    //模板函数声明
    template <typename T>
    int Add(T t1, T t2)
    {
    return t1.i + t2.j;
    }
    可能是你模板函数里的表达式的操作对象和你定义的类有关,不是通常的数据类型,所以如果放在CLASS前面定义会找不到t1,t2的类型,你试试在模板前先声明CLASS或该成头文件申明形式
      

  2.   

    谢谢啊龙,我将模板函数该为下面的形式也不行的。
    template <typename T>
    int Add(T t1, T t2)
    {
    return 10;;
    }按照通常的思维,函数应该先声明再使用。在我的程序里,我希望先声明模板函数,再在类里面使用。但为什么就是不行。
      

  3.   

    也就是说,我下面的程序同样有问题:
    #include <iostream.h>
    #include <tchar.h>//模板函数声明
    template <typename T>
    int Add()
    {
    return 10;
    }//类声明
    class MyClass
    {
    private:
    int i, j;public:
    MyClass() : i(10), j(20) {}
    template <typename T>
    friend int Add();
    };//主函数
    void _tmain()
    {
    MyClass t1, t2;
    int t = Add<MyClass>();
    cout << t;
    }
      

  4.   

    see the link and its relative links below,I think useful :http://www.codeproject.com/atl/atl_underthehood_.asp
      

  5.   

    最简单的程序就是下面这样,但也有问题。我真的搞不懂了饿。
    //模板函数声明与定义
    template <typename T>
    int Add()
    {
    return 10;
    }//类声明与定义
    class MyClass
    {
    public:
    template <typename T>
    friend int Add();
    };//主函数
    void _tmain()
    {
    int t = Add<MyClass>();
    }
      

  6.   

    void _tmain()
    {
    MyClass t1, t2;
    int t = Add<MyClass>();
    cout << t;
    }
    在这个主函数里面,你只要不用到 MyClass ,应该可以的.
    因为模板里面用到了MyClass类,所以,要先定义MyClass
    ==================================================================
    【嘟嘟oοО○●哇靠!!!快让开】
         ╭══╮老婆!开车罗`坐好啊
        ╭╯五档║老公!开慢点`我兴奋 
        ╰⊙═⊙╯。oо○ 压死了不赔! 
      

  7.   

    void _tmain()
    {
    MyClass t1, t2;
    int t = Add<MyClass>();
    cout << t;
    }
    在这个主函数里面,你只要不用到 MyClass ,应该可以的.
    因为模板里面用到了MyClass类,所以,要先定义MyClass
    ==================================================================
    【嘟嘟oοО○●哇靠!!!快让开】
         ╭══╮老婆!开车罗`坐好啊
        ╭╯五档║老公!开慢点`我兴奋 
        ╰⊙═⊙╯。oо○ 压死了不赔! 
      

  8.   

    //Test.h///////////////
    //类声明
    class MyClass
    {
    private:
    int i, j;public:
     MyClass();  template <class T> friend int Add(T t1,T t2);
    };//////////////Test.cpp////////////////////////#include <tchar.h>
    #include "Test.h"//模板函数声明template <class T>  int Add(T t1,T t2)
      
    {
    return t1.i+t2.j;
    }MyClass::MyClass() : i(10), j(20) {}//主函数
    void _tmain()
    {
    MyClass t1, t2;
    int t = Add(t1,t2);
    cout << t;
    }
    以上代码成功运行,似乎问题出在你的友员函数上好象友员函数只能出现在类的申明中,不能在定义中啊,你的类申明定义在一起的,所以出错了,我分开了,通过了VC7全通过啊??那么强啊,我试试 呵呵