首页 > 解决方案 > 返回模板类对象

问题描述

我有一个矩阵类的模板:

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);
}

标签: c++

解决方案


您的复制构造函数是错误的,这会导致这种歧义。

Matrix(Matrix<T>& other);

应该

Matrix(const Matrix<T>& other);

注意:你也会泄漏内存,因为你new[]但没有delete[]


推荐阅读