c++ - 无法在 C++ 的赋值中将 ‘int*’ 转换为 ‘int**’

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

<分区>

我是 C++ 的初学者,所以我开始通过自己编写一点点练习 Vector类(class)。 它存储数组的行数和列数,元素是动态分配的。

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/

最佳答案

最大的错误是在分配指针数组时遗漏了'*':

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

除此之外:

  1. 为什么要将 vector 定义为具有行和列的矩阵?
  2. 分配内存并在不再需要时使用内存
  3. 访问器应该可用

以下面的代码作为起点:

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

关于c++ - 无法在 C++ 的赋值中将 ‘int*’ 转换为 ‘int**’,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564516/

相关文章:

c++ - 无法在没有初始化的情况下声明类?

c++ - D3D11 : variable number of lights in HLSL

javascript - 在 Javascript 中单击之前执行按钮方法

javascript 'this' 用法

将 *char 转换为 int 时出现 C++ 错误

c++ - 继承的典型问题

android - Android 中的按钮数组

Java:如何测试数组相等性?

javascript - 谁能帮忙解释一下这个JavaScript算法 [].filter.call()

mysql - .NET - 通过连接到数据库导入类