"No viable overloaded =" nullptr

"No viable overloaded =" nullptr

我刚开始使用 C++,一直卡在移动构造函数上。这是我的 .cpp:

SimpleMatrix::SimpleMatrix(SimpleMatrix &&other_mat) {
 cols = other_mat.cols;
 rows = other_mat.rows;
 data_ = other_mat.data_;
 other_mat.cols = 0;
 other_mat.rows = 0;
 other_mat.data_ = nullptr; // <- Error here
}

我在 other_mat.data_ = nullptr 处遇到 No viable overloaded = 错误。什么地方出了错?这是我初始化矩阵的方式吗?

以下是 .hpp 文件中的相关部分:

class SimpleMatrix {
 public:
  SimpleMatrix(std::size_t nrows, std::size_t ncols);
  SimpleMatrix(std::initializer_list<std::initializer_list<double>> data);
  SimpleMatrix(SimpleMatrix&& other_mat);
  SimpleMatrix& operator=(SimpleMatrix&& other_mat);

 private:
  std::vector<std::vector<double> > data_;
  int rows, cols;
};

data_是一个向量非指针对象nullptr是初始化一个指针到是一个空指针。

您不能将非指针变量指定为空指针。而C++没有任何空值或对象的概念。

如果你想正确初始化向量,我建议你添加一个构造函数初始化列表:

SimpleMatrix::SimpleMatrix(SimpleMatrix &&other_mat)
    : data_(std::move(other_mat.data_))  // Move the data from the other vector
    , rows(other_mat.rows)
    , cols(other_mat.cols)
{
    // Clear the other matrix rows and cols
    other_mat.rows = 0;
    other_mat.cols = 0;
}

或者,您可以依赖 the rule of zero 并让编译器生成的构造函数为您处理所有事情,在这种情况下它应该正确地完成:

class SimpleMatrix {
 public:
  SimpleMatrix(SimpleMatrix &&) = default;
  // ...
};