0

我正在用 C++ 中的模板开发一个通用的 {int,short,double} 多维数组结构。

template <typename T>
struct Array {
   T *x;
   int size;
   int nDims;
   int N[ARRAYMAXNDIMS];
};

我在申报方面没有问题。但是,当我在函数调用中使用它时会出现问题。请帮我纠正错误。我在这里附上源代码并编译错误。

非常感谢,等待您的回复。

//============================================================================
// parse file parameter to memory
#include <cmath>
#include <cstdio>
#include <string>
#include <cstdlib>

#define ARRAYMAXNDIMS 4

using namespace std;

// multi-dimensional integer array with at most 4 dimensions
template <typename T>
struct Array {
   T *x;
   int size;
   int nDims;
   int N[ARRAYMAXNDIMS];
};

template <typename T> Array<T> reduceArrayDimension(Array<T> *a);

int main()
{
    Array<int> num;
    num.nDims = 4; 
    num.size = 16; 
    num.N[0] = 2; num.N[1] = 2; num.N[2] = 2; num.N[3] = 2;
    num.x = (int *)calloc(num.size,sizeof(int));

    for (int i=0;i < num.size; i++) {
        num.x[i] = i;
    };

    Array<int> b = reduceArrayDimension(&num);

    return 0;
}

template <typename T> Array<T> reduceArrayDim(Array<T> *a) {
// reduce 4D-array to 3D-array: [0,1,2,3] -> [0,1,2]
// B[i,j,k] = sum (A[i,j,k,l]) for all index l

    Array<T> b;

    b.nDims = 3;
    int ax1 = a->N[0], ax2 = a->N[1], ax3 = a->N[2], ax4 = a->N[3];

    b.N[0] = ax1; b.N[1] = ax2; b.N[2] = ax3; b.N[3] = 1;
    b.size = ax1*ax2*ax3;
    b.x = (T *)calloc(b.size,sizeof(T));

    int sum = 0;
    for (int i = 0; i < ax1; i++)
        for (int j = 0; j < ax2; j++)
            for (int k = 0; k < ax3; k++) {
                sum = 0;
                for (int l = 0; l <  ax4; l++)
                    sum += a->x[i + j*ax1 + k*ax1*ax2 + l*ax1*ax2*ax3];
                b.x[i + j*ax1 + k*ax1*ax2] = sum;   // sum over dimension 4
            }
    return b;
}

错误日志:

$ g++ main1.cpp 
/tmp/ccFwJ3tA.o: In function `main':
main1.cpp:(.text+0xba): undefined reference to `Array<int> reduceArrayDimension<int>(Array<int>*)'
collect2: error: ld returned 1 exit status
4

1 回答 1

2

宣言reduceArrayDimension

定义reduceArrayDim

所以,没有定义,reduceArrayDimension这就是为什么这里有未定义的引用。

于 2013-04-04T05:54:24.633 回答