簡體   English   中英

C++ 模板類運算符重載

[英]C++ template class operators overloading

最近我一直在研究矩陣類,一切都很好,直到我嘗試實現+運算符。 我只是不明白為什么它不起作用。 我查看了許多 GitHub 頁面以了解其他人是如何實現它的,但仍然無法在我的代碼中找到任何問題。

我的課是這樣的:

template<class type = int>
    class matrix{
    private:
        int WIDTH, HEIGHT;
        int ROWS, COLS;
        type* array;
}

構造函數:

template<class type>
matrix<type>::matrix() : WIDTH(0), HEIGHT(0), ROWS(0), COLS(0), array(nullptr) {}

復制構造函數:

template<class type>
matrix<type>::matrix(const matrix& matrixObj) : WIDTH(matrixObj.WIDTH), COLS(matrixObj.WIDTH), HEIGHT(matrixObj.HEIGHT), ROWS(matrixObj.HEIGHT), array(matrixObj.array){}

析構函數:

template<class type>
matrix<type>::~matrix(){
    WIDTH = COLS = 0;
    HEIGHT = ROWS = 0;
    delete[] array;
}

=運算符

template<class type>
matrix<type>& matrix<type>::operator=(matrix matObj) noexcept {
    swap(*this, matObj);
    return *this;
}

+=運算符

template<class type>
matrix<type>& matrix<type>::operator+=(const matrix& matObj) {
    if (matObj.WIDTH != this->WIDTH || matObj.HEIGHT != this->HEIGHT)
        throw std::runtime_error("Both matrices must have same dimensions!");

    for (int i = 0; i < WIDTH * HEIGHT; i++)
        array[i] += matObj.array[i];
    return *this;
}

+運算符

template<typename type>
matrix<type> operator+(matrix<type> lhs, matrix<type>& rhs){
    return lhs += rhs;
}

當我嘗試運行以下代碼時:

matrix<int> mat1(2, 3), mat3(2, 5), mat2;
mat2 = mat1 + mat3;

它為mat1mat2返回一些隨機垃圾值。

我該如何解決?

編輯

我已經實現了如下所示的重載構造函數:

template<class type>
matrix<type>::matrix(int size, type values = 0) : WIDTH(size), HEIGHT(size), ROWS(size), COLS(size) {
    int iter = size * size;
    delete[] array;
    this->array = new type[iter];
    while (iter--)
        array[iter] = values;
}

您不會在任何地方將數組初始化為nullptr以外的任何內容,因此對array任何使用都會導致未定義的行為。

您的復制構造函數需要復制數組,而不僅僅是復制指針。

解決所有這些問題的最簡單方法是使用std::vector

template<class type = int>
    class matrix{
    public:
        matrix() : WIDTH(0), HEIGHT(0), ROWS(0), COLS(0) {}
    private:
        int WIDTH, HEIGHT;
        int ROWS, COLS;
        std::vector<type> array;
};

以上不需要復制構造函數、賦值運算符或析構函數,因為編譯器生成的默認值做正確的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM