BlinCT
BlinCT3. April 2017 05:07

Перегрузка оператор + для класса матрицы

C++

Всем привет. Вопрос состоит в реализации перегрузки оператора. Думаю что я что то не правильно указываю так как класс шаблонный а с этим опыта не много. Ниже укажу хедер класса и реализацию, надеюсь кто то подскажет что не так у меня в коде. CustomMatrix.hpp

#pragma once

#include <QVector>


template <typename T>
friend CustomMatrix<T> &operator+(const CustomMatrix &a, const CustomMatrix &b);
template <typename T>
friend CustomMatrix &operator*(const CustomMatrix &a, const CustomMatrix &b);

template <typename T>
class CustomMatrix
{
public:
    //CustomMatrix();
    CustomMatrix<T> TopLeftCorner(int i, int j);
    CustomMatrix(const CustomMatrix &) = default;
    CustomMatrix(CustomMatrix &&) = default;

    CustomMatrix(int rowSize, int colSize);

    const T at(int x, int y) const;
    T & at(int x, int y);

    ~CustomMatrix() = default;
private:
    int m_iRowSize;
    int m_iColSize;

    QVector<T> m_arrVector;
};

#include "CustomMatrix_impl.hpp"
А тут уже реализация перегрузки: CustomMatrix_impl.hpp
template<typename T>
CustomMatrix &operator+(const CustomMatrix &a, const CustomMatrix &b)
{
    CustomMatrix c;

    if(a.m_iColSize == b.m_iColSize && a.m_iRowSize == b.m_iRowSize)
    {
        for (int i = 0; i < a.m_iRowSize; ++i)
        {
            for (int j = 0; j < a.m_iColSize; ++j)
            {
                c.at(i, j) = a.at(i, j) + b.at(i, j);
            }
        }
    }
    return c;
}

template<typename T>
CustomMatrix &operator*(const CustomMatrix &a, const CustomMatrix &b)
{
    CustomMatrix c;

    if(a.m_iColSize == b.m_iRowSize)
    {
        for (int i = 0; i < a.m_iColSize; ++i)
        {
            for (int j = 0; j < a.m_iRowSize; ++j)
            {
                T sum = 0;
                for (int k = 0; k < a.m_iColSize; ++k)
                {
                    sum = sum + a.at(i, k) * b.at(k, j);
                }
                c.at(i, j) = sum;
            }
        }
    }
    return c;
}
Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

2
BlinCT
  • 3. April 2017 06:29

Переделал все без шаблона хедер:

friend CustomMatrix &operator+(const CustomMatrix &a, const CustomMatrix &b);
friend CustomMatrix &operator*(const CustomMatrix &a, const CustomMatrix &b);

class CustomMatrix
{
public:
    //CustomMatrix();
    CustomMatrix<T> TopLeftCorner(int i, int j);
    CustomMatrix(const CustomMatrix &) = default;
    CustomMatrix(CustomMatrix &&) = default;

    CustomMatrix(int rowSize, int colSize);

    const double at(int x, int y) const;
    double & at(int x, int y);

    ~CustomMatrix() = default;
private:
    int m_iRowSize;
    int m_iColSize;

    QVector<double> m_arrVector;
};
И сама реализация:
CustomMatrix &operator+(const CustomMatrix &a, const CustomMatrix &b)
{
    CustomMatrix c(m_iRowSize, m_iColSize);

    if(a.m_iColSize == b.m_iColSize && a.m_iRowSize == b.m_iRowSize)
    {
        for (int i = 0; i < a.m_iRowSize; ++i)
        {
            for (int j = 0; j < a.m_iColSize; ++j)
            {
                c.at(i, j) = a.at(i, j) + b.at(i, j);
            }
        }
    }
    return c;
}

CustomMatrix &operator*(const CustomMatrix &a, const CustomMatrix &b)
{
    CustomMatrix c;

    if(a.m_iColSize == b.m_iRowSize)
    {
        for (int i = 0; i < a.m_iColSize; ++i)
        {
            for (int j = 0; j < a.m_iRowSize; ++j)
            {
                T sum = 0;
                for (int k = 0; k < a.m_iColSize; ++k)
                {
                    sum = sum + a.at(i, k) * b.at(k, j);
                }
                c.at(i, j) = sum;
            }
        }
    }
    return c;
}
    Evgenii Legotckoi
    • 3. April 2017 06:35
    • Die Antwort wurde als Lösung markiert.

    День добрый.
    Думаю, что объявление friend стоит поместить внутрь класса.

    class CustomMatrix
    {
    public:
        //CustomMatrix();
        CustomMatrix<T> TopLeftCorner(int i, int j);
        CustomMatrix(const CustomMatrix &) = default;
        CustomMatrix(CustomMatrix &&) = default;
    
        CustomMatrix(int rowSize, int colSize);
    
        friend CustomMatrix &operator+(const CustomMatrix &a, const CustomMatrix &b)
        {
            CustomMatrix c(m_iRowSize, m_iColSize);
    
            if(a.m_iColSize == b.m_iColSize && a.m_iRowSize == b.m_iRowSize)
            {
                for (int i = 0; i < a.m_iRowSize; ++i)
                {
                    for (int j = 0; j < a.m_iColSize; ++j)
                    {
                        c.at(i, j) = a.at(i, j) + b.at(i, j);
                    }
                }
            }
            return c;
        }
    
        friend CustomMatrix &operator*(const CustomMatrix &a, const CustomMatrix &b)
        {
            CustomMatrix c;
    
            if(a.m_iColSize == b.m_iRowSize)
            {
                for (int i = 0; i < a.m_iColSize; ++i)
                {
                    for (int j = 0; j < a.m_iRowSize; ++j)
                    {
                        T sum = 0;
                        for (int k = 0; k < a.m_iColSize; ++k)
                        {
                            sum = sum + a.at(i, k) * b.at(k, j);
                        }
                        c.at(i, j) = sum;
                    }
                }
            }
            return c;
        }
    
        const double at(int x, int y) const;
        double & at(int x, int y);
    
        ~CustomMatrix() = default;
    private:
        int m_iRowSize;
        int m_iColSize;
    
        QVector<double> m_arrVector;
    };

      Kommentare

      Nur autorisierte Benutzer können Kommentare posten.
      Bitte Anmelden oder Registrieren
      Letzte Kommentare
      A
      ALO1ZE19. Oktober 2024 08:19
      Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
      ИМ
      Игорь Максимов5. Oktober 2024 07:51
      Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
      d
      dblas55. Juli 2024 11:02
      QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
      k
      kmssr8. Februar 2024 18:43
      Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
      Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
      Jetzt im Forum diskutieren
      J
      JacobFib17. Oktober 2024 03:27
      добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
      JW
      Jhon Wick1. Oktober 2024 15:52
      Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
      КГ
      Кирилл Гусарев27. September 2024 09:09
      Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
      F
      Fynjy22. Juli 2024 04:15
      при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

      Folgen Sie uns in sozialen Netzwerken