错误:不匹配'operator>>'在'in>> *(arr +((long unsigned int)(((long unsigned int)i)* 8ul)))'

时间:2013-03-04 19:08:49

标签: c++ templates

对于我在函数加载中的作业,我实例化一个ifstream对象打开一个文件并开始读入,得到很长的编译错误。 我也尝试通过重定向输入来摆脱fstream和使用cin,但我从来没有这么远。完全相同的错误除了使用cin而不是in。

    #ifndef _BUBBLE_SORT_H
    #define _BUBBLE_SORT_H

    #include <iostream>
    #include <fstream>
    #include <cstdlib>

    using namespace std;

    template <typename T>
    void swap(T *a, T *b){
            T t = *a; 
            *a = *b; 
            *b = t;
    }

    template <typename T>
    void bubbleSort(T * arr, int n){ 
            bool isSorted = false;
            for (int last = n-1; last > 0 && !isSorted; last--) {
                    isSorted = true;
                    for (int i = 0; i < last; i++)
                            if (arr[i] > arr[i+1]) {
                                    swap((arr+i), (arr+i+1));
                                    isSorted = false;
                             }
                    if (last % 1000 == 0) cerr << ".";
            }
    }

    template <typename T>
    void print(T arr[], int n){ 
            for(int i = 0; i < n; i++)
                    cout << arr[i] << '\t';
    }

    template <typename T>
    T &load(string filename, int &n){
            ifstream in; 
            in.open(filename.c_str());

            in >> n;
            if(!in) {
                    cerr << "Error opening file" ;
                    exit(1);
            }   
            T *arr = new T[n];

            for(int i = 0; i < n; i++)
                    in >> *(arr + i); 
            in.close();
            return *arr;
    } 

#endif

我正在使用gnu gcc编译器

1 个答案:

答案 0 :(得分:1)

问题在于对load函数的调用。你在打电话吗,表明你正在阅读的阵列类型?这里有一个建议,用于编辑加载函数以返回数组,以及主函数中的调用者:

template <typename T>
T *load(string filename, int &n){
        ifstream in; 
        in.open(filename.c_str());

        in >> n;
        if(in.fail()) {
                cerr << "Error opening file" ;
                exit(1);
        }   
        T *arr = new T[n];

        for(int i = 0; i < n; i++)
                in >> *(arr + i); 
        in.close();
        return arr;
} 

int main(){
        int x, i;
        string fileName = "test.txt";
        double *arr = load<double>(fileName, x); // make sure you have <double> in the call
        for(i = 0; i < x; i++) cout << arr[i] << endl;
        delete [] arr;
        return 0;
        }

请确保包括您正在阅读的数组类型,比方说,加倍,否则您将收到错误。另外,根据我的拙见,最好返回一个指针,如上面的代码段所示。希望有所帮助。

修改

模板工作方式多一点。编译代码时,模板会扩展为同一函数的许多不同版本,具体取决于整个程序中使用了多少不同类型(并用T表示)。因此,考虑到并查看问题中提出的代码,尝试从文件输入流读取到类型T是没有意义的,因为编译器无法扩展到基于未知类型的任何函数。但是,当模板变量T的类型已知时(在typename都出现在函数参数中的情况下),<double>规范可能会被省略,因为它是从函数调用中传递的参数类型。