0

У меня есть шаблонный класс TMatrix

template <class Type>
class TMatrix {
Type** array;
int countLine; //Количество строчек
int countColum; //Количество столбцов
Public:
\\...
}

И другой класс дробное число Fractional

class Fractional {
int dividend; //Делимое
int divider; //Делитель
}

Как перегрузить [][] чтобы при array[i][j] в котором массив Fractional у меня возвращалось дробное число То есть чтобы выполнялось double value = array[i][j] в методе класса TMatrix

4
  • 1
    if constexpr (std::is_same_v<Type, Fractional>)
    – tocic
    16 окт 2022 в 19:45
  • Вы точно хотите использовать Type** а не vector<vector<Type>>?
    – TheRyuTeam
    17 окт 2022 в 10:31
  • Задание такое, мы по программе еще не должны знать библиотеки STL
    – Nayt
    17 окт 2022 в 12:02
  • @Nyat для чего вообще такое поведение? Как звучит задача то?
    – TheRyuTeam
    17 окт 2022 в 12:47

1 ответ 1

0

Вижу такие решения. Это простой вариант: определить метод у Fractional для вычисления

#include <iostream>

template <class T>
class TMatrix
{
public:
    TMatrix(const unsigned nRow, const unsigned nCol):
        _nRow(nRow),
        _nCol(nCol),
        _data(new T*[nRow])
    {
        for (unsigned i = 0; i < _nRow; ++i)
            _data[i] = new T[_nCol] { T() };
    }

    unsigned rows() const noexcept
    {
        return _nRow;
    }

    unsigned cols() const noexcept
    {
        return _nCol;
    }

    T* operator[](unsigned i)
    {
        if (i > _nRow)
            throw std::out_of_range("");
        
        return _data[i];
    }

private:
    unsigned _nRow; //Количество строчек
    unsigned _nCol; //Количество столбцов
    T** _data;
};

struct Fractional
{

    operator double() const
    {
        return double(dividend) / divider;
    }

    int dividend = 0; //Делимое
    int divider = 0; //Делитель
};


int main()
{
    TMatrix<Fractional> matrix(5, 5);

    for (unsigned row = 0; row < matrix.rows(); ++row)
    {
        for (unsigned col = 0; col < matrix.cols(); ++col)
        {
            Fractional& val = matrix[row][col];
            val.dividend = rand();
            val.divider = rand() + 1;

            std::cout << val.dividend << " / " << val.divider << " = " << (double)matrix[row][col] << '\n';
        }
    }
    return 0;
}

Но так не выполняется Ваш вопрос: значение должна вычислить матрица при вызове.

Для этого я попробовал написать класс вектора, который при вызове operator отправлял функтору свои данные и индекс, и этот функтор уже сам вычисляет значение(по дефолту просто возвращает data[i])

#include <iostream>
#include <vector>
#include <type_traits>
#include <ctime>

template <class T>
class ArrayValueGetter
{
public:
    T& operator()(T* data, std::size_t index)
    {
        return data[index];
    }

    T operator()(const T* data, std::size_t index)
    {
        return data[index];
    }
};

template <class T, class CustomValueGetter = ArrayValueGetter<T>, class Enable = void>
class CustomVector: public std::vector<T>
{
public:
    using Base = std::vector<T>;
    using Base::Base;

    auto operator[](typename Base::size_type i) const
    {
        return CustomValueGetter()(Base::data(), i);
    }
};

template <class T, class CustomValueGetter>
class CustomVector<T, CustomValueGetter, typename std::enable_if<std::is_reference<
            typename std::result_of<CustomValueGetter(T*, std::size_t)>::type
        >::value>::type>
        : public std::vector<T>
{
public:
    using Base = std::vector<T>;
    using Base::Base;

    auto& operator[](typename Base::size_type i)
    {
        return CustomValueGetter()(Base::data(), i);
    }

    auto operator[](typename Base::size_type i) const
    {
        return CustomValueGetter()(Base::data(), i);
    }
};

template <class T, class CustomValueGetter = ArrayValueGetter<T>>
class TMatrix
{
public:
    TMatrix(int nRow, int nCol):
        _matrix(nRow, CustomVector<T, CustomValueGetter>(nCol, T())),
        _nCols(nCol)
    {
    }

    int rows() const noexcept
    {
        return _matrix.size();
    }

    int cols() const noexcept
    {
        return _nCols;
    }

    auto begin()
    {
        return _matrix.begin();
    }

    auto end()
    {
        return _matrix.end();
    }

    auto begin() const
    {
        return _matrix.begin();
    }

    auto end() const
    {
        return _matrix.end();
    }

    CustomVector<T, CustomValueGetter>& operator[](unsigned i)
    {
        return _matrix[i];
    }

    const CustomVector<T, CustomValueGetter>& operator[](unsigned i) const
    {
        return _matrix[i];
    }
private:
    CustomVector<CustomVector<T, CustomValueGetter>> _matrix;
    int _nCols;
};

struct Fractional
{
    int dividend; //Делимое
    int divider; //Делитель
};

struct FractionalValueGetter
{
    double operator()(const Fractional* data, std::size_t i)
    {
        auto& ref = data[i];
        return double(ref.dividend) / ref.divider;
    }
};

int main()
{
    srand(time(0));

    TMatrix<Fractional, FractionalValueGetter> matrix(5, 5);
    for (auto& r: matrix)
        for (auto& c: r)
            c = Fractional{rand(), rand() + 1};

    std::cout << "Matrix(" << matrix.rows() << ", " << matrix.cols() << ")\n";

    for (unsigned row = 0; row < matrix.rows(); ++row)
    {
        for (unsigned col = 0; col < matrix.cols(); ++col)
        {
            std::cout << matrix[row][col] << '\n';
        }
    }
    return 0;
}

Просьба раскритиковать этот код в пух и прах, впервые пишу подобное)

3
  • 1
    пожалуйста, постарайтесь оставлять чуть более развёрнутые ответы. дополнить ответ можно, нажав править 17 окт 2022 в 9:52
  • @DaniilLoban добавил развернутый ответ
    – TheRyuTeam
    17 окт 2022 в 12:16
  • @aleksandrbarakin добавил развернутый ответ
    – TheRyuTeam
    17 окт 2022 в 12:16

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.