V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
qianfeilong
V2EX  ›  C

类模板不能多次使用吗?

  •  
  •   qianfeilong · 2018-07-09 17:34:35 +08:00 · 2464 次点击
    这是一个创建于 2089 天前的主题,其中的信息可能已经有所发展或是发生改变。

    #include<iostream> using namespace std;

    template<class t=""> int length(T& data) { return sizeof(data) / sizeof(data[0]); }

    void bubblesort(T& data1) { int size; size = length(arr); data1[0] = 1;

    } void main()
    { int arr[6] = { 5,3,6,2,6,1 }; bubblesort(arr);

    system("pause");
    

    }

    想实现一下冒泡排序,用一下类模板,void bubblesort(T& data1)在这行中 T 无法被编译器识别出来,怎么回事啊。

    7 条回复    2018-07-10 11:06:51 +08:00
    pagict
        1
    pagict  
       2018-07-09 17:53:34 +08:00
    先指出一个 typo
    lz 想写的应该是

    ```cpp
    template<class T="">...
    ```


    那么以上写法的问题是,T 应该是一个类型,在```bubblesort```实例化时,由于模板参数列表为空,编译器去找默认类型,而你提供的默认类型居然是```=""```,这不是类型这是值啊,当然实例化失败,于是编译报错了
    dorentus
        2
    dorentus  
       2018-07-09 19:34:10 +08:00 via iPhone
    我不会 C++,随便再补充一下:

    你上面只是写了两个模板函数吧,哪里有类啦……
    这两个函数又没啥关系…
    MeteorCat
        3
    MeteorCat  
       2018-07-09 19:48:42 +08:00 via Android
    template<typename T>
    void bubblesort(T &data){
    .......
    }

    这样的?楼主需要看下模板编程的书籍,你写的模板错漏百出
    xiri
        4
    xiri  
       2018-07-09 20:56:20 +08:00 via Android
    @dorentus 我也想说,楼主写的这哪里有类,看做模板函数的话又一堆错误
    xiri
        5
    xiri  
       2018-07-09 21:02:51 +08:00
    ```
    #include <iostream>
    using namespace std;

    template <class numtype>
    class Sort
    {
    public:
    Sort(int n, numtype m[]) :num(n) //构造函数,通过参数初始化表实现初始化
    {
    for (int i = 0; i < num; i++)Num[i] = m[i];
    }
    ~Sort()
    {
    delete[] Num; //析构函数,释放 new 开辟的空间
    }
    // void Select();
    void Bubble();
    // void Insert();
    void Print();
    private:
    int num;
    numtype *Num = new numtype[num]; //使用 new 动态定义元素数组
    };
    ```

    函数在类外定义:

    ```
    template <class numtype>
    void Sort<numtype>::Bubble() //冒泡排序法
    {
    for (int i = 0; i < num-1; i++)
    {
    for (int j = 0; j < num-1-i; j++)
    {
    if (Num[j]>Num[j + 1])
    {
    numtype t = Num[j];
    Num[j] = Num[j + 1];
    Num[j + 1] = t;
    }
    }
    }
    }
    ```

    很久之前写的了,是一个包含三种排序算法的排序类,这里只贴了冒泡排序的,命名这些比较乱,不要在意了
    xiri
        6
    xiri  
       2018-07-09 21:04:42 +08:00
    @xiri 额,,,,,不会 V2EX 的排版
    qianfeilong
        7
    qianfeilong  
    OP
       2018-07-10 11:06:51 +08:00
    明白了 我把类模板和模板函数概念混淆了 感谢各位的回答
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1278 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:29 · PVG 07:29 · LAX 16:29 · JFK 19:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.