在C ++中赋值时不能将'int *'转换为'int **'

时间:2014-10-25 16:15:47

标签: c++ arrays class templates dynamic-memory-allocation

我是C ++的初学者,所以我开始练习自己的Vector课程。 它存储数组的行数和列数,并且元素是动态分配的。

template <class T> 
class Vector {
    private:
        unsigned int rows;
        unsigned int cols;
        T **elements;
    public:
        Vector(unsigned int, unsigned int);
        ~Vector();
};

template <class T>
Vector<T>::Vector(unsigned int rows, unsigned int cols) {
    this->rows = rows;
    this->cols = cols;

    this->elements = new T[this->rows];
    for (int i = 0; i < this->rows; i++) {
        this->elements[i] = new T[this->cols];
    }
}

template <class T>
Vector<T>::~Vector() {
};

这是代码。当我编译它时(我创建了一个对象来测试它:Vector<int> test;),我收到错误:"Cannot convert ‘int*’ to ‘int**’ in assignment"

为什么我收到此错误?我在网上看到了多维动态分配示例:http://www.cplusplus.com/forum/beginner/63/

1 个答案:

答案 0 :(得分:2)

最大的错误是您错过了*&#39;在分配指针数组时:

this->elements = new T*[this->rows];

除此之外:

  1. 为什么要将矢量定义为包含行和列的矩阵?
  2. 在您不再需要时分配和使用后的可用内存
  3. 访问者应该可用
  4. 作为起点,请使用以下代码:

    template <class T> 
    class Vector {
        public:
            unsigned int rows;
            unsigned int cols;
            T** elements;
            Vector(unsigned int, unsigned int);
            ~Vector();
    };
    
    template <class T>
    Vector<T>::Vector(unsigned int rows, unsigned int cols) {
        this->rows = rows;
        this->cols = cols;
    
        this->elements = new T*[this->rows];
        for (int i = 0; i < this->rows; i++) {
            this->elements[i] = new T[this->cols];
        }
    }
    
    template <class T>
    Vector<T>::~Vector() {
        for(int i=0; i<this->rows;++i)
            delete[] this->elements[i];
        delete[] this->elements;
    };
    
    
    int main()
    {
        Vector<int> obj(2,2);
        obj.elements[0][0] = 1;
        obj.elements[0][1] = 2;
        obj.elements[1][0] = 3;
        obj.elements[1][1] = 4;
    
        std::cout << obj.elements[0][0] << " " << obj.elements[0][1] << std::endl;
        std::cout << obj.elements[1][0] << " " << obj.elements[1][1] << std::endl;
    
        return 0;
    }
    

    Example