c++ - 返回模板类对象
问题描述
我有一个矩阵类的模板:
template <typename T>
class Matrix {
许多函数(比如添加两个矩阵)返回 std::optional。我想制作一个可以解开值(或抛出异常)的运算符:
template <class T>
Matrix<T> operator!(const std::optional<Matrix<T>>& other) {
return other.value();
}
这样做我得到错误 C2440:“无法使用 [_Ty = Matrix] 从 const _Ty 转换为 Matrix<int>”。它说由于复制构造函数不明确或复制构造函数不可用,无法完成 Matrix 类的构造。
编辑:
#include <iostream>
#include <optional>
template <typename T>
class Matrix {
private:
T** matrix;
int sizeX;
int sizeY;
public:
Matrix(int x, int y);
Matrix(Matrix<T>& other);
Matrix(Matrix<T>&& other);
void set_value(T val, int x, int y);
std::optional<Matrix<T>> vec_from_col(int colIndex);
};
template <typename T>
Matrix<T>::Matrix(int x, int y) {
std::cout << "Matrix Param\n";
if (x <= 0 || y <= 0) {
return;
throw -1;
}
else {
matrix = new T*[x];
for (int i = 0; i < x; i++) {
matrix[i] = new T[y];
for (int j = 0; j < y; j++) {
matrix[i][j] = 0;
}
}
sizeX = x;
sizeY = y;
}
}
template <typename T>
Matrix<T>::Matrix(Matrix<T>& other) {
std::cout << "Matrix Copy\n";
sizeX = other.sizeX;
sizeY = other.sizeY;
matrix = new T*[sizeX];
for (int i = 0; i < sizeX; i++) {
matrix[i] = new T[sizeY];
for (int j = 0; j < sizeY; j++) {
matrix[i][j] = other.matrix[i][j];
}
}
}
template <typename T>
Matrix<T>::Matrix(Matrix<T>&& other) {
std::cout << "Matrix Move\n";
sizeX = other.sizeX;
sizeY = other.sizeY;
matrix = other.matrix;
other.matrix = NULL;
}
template <typename T>
void Matrix<T>::set_value(T val, int x, int y) {
if (x < 0 || x >= sizeX || y < 0 || y >= sizeY) {
std::cout << "Invalid index was given. Matrix was unchanged.\n";
return;
}
else {
matrix[x][y] = val;
}
}
template <typename T>
std::optional<Matrix<T>> Matrix<T>::vec_from_col(int colIndex) {
if (colIndex < 0 || colIndex >= sizeX) {
return {};
}
Matrix<T> newVec(1, sizeY);
for (int i = 0; i < sizeY; i++) {
newVec.set_value(matrix[colIndex][i], 0, i);
}
return newVec;
}
template <class T>
Matrix<T> operator!(const std::optional<Matrix<T>>& other) {
return other.value();
}
int main() {
Matrix<int> test(2, 3);
test.set_value(10, 0, 1);
test.set_value(5, 0, 0);
test.set_value(13, 0, 2);
test.set_value(8, 1, 0);
Matrix<int> vec = !test.vec_from_col(0);
}
解决方案
您的复制构造函数是错误的,这会导致这种歧义。
Matrix(Matrix<T>& other);
应该
Matrix(const Matrix<T>& other);
注意:你也会泄漏内存,因为你new[]
但没有delete[]
。
推荐阅读
- amazon-dynamodb - 扫描整个发电机数据库并根据条件更新记录
- flutter - 颤振 - ImagePicker 问题
- c++ - 如何在 C++ 中找到序列中最大元素的出现次数?
- html - grunt build 卡在正在运行的任务中 (ngtemplates:dist)
- python - ValueError:无法将字符串转换为浮点数:'samples.txt'
- r - 将数据框作为函数参数传递,但在函数调用中使用其名称作为字符串
- php - 我们如何使用 foreach 循环为特征内的模型字段赋值
- azure-service-fabric - 您可以将 Service Fabric 集群移动到另一个子网吗?
- google-apps-script - TypeError:无法在谷歌工作表脚本中读取 null 的属性“getRange”(第 6 行,文件“代码”)
- laravel - Laravel Carbon 类时间戳