我上这堂课

namespace baseUtils {

template<typename AT>
class growVector {

        int size;
        AT **arr;
        AT* defaultVal;

    public:

        growVector(int size, AT* defaultVal );   //Expects number of elements (5) and default value (NULL)
        AT*& operator[](unsigned pos);
        int length();
        void reset(int pos);    //Resets an element to default value
        void reset();           //Resets all elements to default value
        ~growVector();
};

}


这是operator []的实现

template<typename AT>
AT*& growVector<AT>::operator [](unsigned pos){
    if (pos >= size){
        int newSize = size*2;
        AT** newArr = new AT*[newSize];
        memcpy(newArr, arr, sizeof(AT)*size);
        for (int i = size; i<newSize; i++)
            newArr[i] = defaultVal;
        size = newSize;
        delete arr;
        arr = newArr;
    }
    return arr[pos];
}


(是的,我的确意识到我不检查size * 2> = pos ...但这不是重点)
如果我在类似的代码中使用它:

int main() {

    growVector<char> gv();
    char* x = NULL;
    for (int i = 0; i< 50; i++){
        gv[i] = x;
    }
    gv.reset();
    return 0;
}


编译器说

../src/base.cpp:98: warning: pointer to a function used in arithmetic
../src/base.cpp:98: error: assignment of read-only location ‘*(gv + ((unsigned int)i))’
../src/base.cpp:98: error: cannot convert ‘char*’ to ‘baseUtils::growVector<char>()’ in assignment


参照线gv [i] = x; (似乎没有看到[]的重新定义)

为什么????我想念什么?



更正构造函数问题后,我有了链接器sayng:

/home/dario/workspace/base/Debug/../src/base.cpp:95: undefined reference to `baseUtils::growVector<char>::growVector(int, char*)'
/home/dario/workspace/base/Debug/../src/base.cpp:98: undefined reference to `baseUtils::growVector<char>::operator[](unsigned int)'
/home/dario/workspace/base/Debug/../src/base.cpp:100: undefined reference to `baseUtils::growVector<char>::reset()'
/home/dario/workspace/base/Debug/../src/base.cpp:101: undefined reference to `baseUtils::growVector<char>::~growVector()'
/home/dario/workspace/base/Debug/../src/base.cpp:101: undefined reference to `baseUtils::growVector<char>::~growVector()'


像它无法链接...为什么? :O

最佳答案

问题是你的声明

growVector<char> gv();


编译器将此解释为声明一个名为gv的函数,该函数返回一个growVector<char>,而不是您所意图的对象。由于没有默认的构造函数,因此无论如何都不会编译。更改为:

growVector<char> gv(0,0);

10-01 14:33