C ++ how to create a double class operator [] []

I am creating a type to be able to control matrices, so I was looking for how to make the [] [] operator, but no luck, so any idea how to do this, I just need a way to make a double operator this is the class am building

#include<iostream>
#include<conio.h>

using namespace std;

class ddouble{
private:
unsigned short int  x, y;
public:
ddouble();
ddouble(unsigned short int, unsigned short int);
double **M;
void read();
void print();
};

ddouble::ddouble(unsigned short int m, unsigned short int n){
for (int i = 0; i < m; i++){
    M = new (nothrow) double *[i];
    for (int I = 0; I < n; I++){
        M[i] = new (nothrow) double[I];
    }
}
}
void ddouble::read(){
for (int i = 0; i < x; i++){

    cout << "plz enter line \n";

    for (int I = 0; I < y; I++){
        cin >> M[i][I];
    }
}
}
void ddouble::print(){

cout << "i,j\t|\t";

for (int i = 0; i < y; i++){
    cout << i << "\t";
}

cout << endl;

for (int i = 0; i < x; i++){

    cout << i << "\t|\t";

    for (int I = 0; I < y; I++){
        cout << M[i][I] << "\t";
    }

    cout << endl;
}
} 

void main(){

ddouble a(2, 2);
a.read();
a.print();

_getch();
}
+4
source share
3 answers

I would recommend using std::vector<std::vector<double>>. However, given the structure you currently have, you can simply determine operator[]which one returns double *, for example:

double * ddouble::operator[](int i) {
    return M[i];
}

Now you can access your variable in mainhow a[i][j].

In addition, you are missing a destructor that frees memory; without it, you have memory leaks. You must define the destructor as:

void ddouble::~ddouble() {
    for(int I = 0; I < y; I++) {
        delete [] M[I];
    }

    delete [] M;
}
+4

. ( operator()), .

[][], , , operator[], .

class proxy {
    double * p;
public:
    proxy(double * p) : p(p) {}
    double & operator[](size_t i) {return p[i];}
};

proxy operator[](size_t i) {return proxy(M[i]);}

const-correctness .

double*; , , .

( , , ).

+4

-, . - : -

template<class T>
class Array2D 
{
  public:
    class Array1D 
    {
      public:
        T& operator[](int index);
        const T& operator[](int index) const;
        ...
    };
    Array1D operator[](int index);
    const Array1D operator[](int index) const;
    ...
};

-. std::vector<std::vector<double> >. , , , .....

+2

Source: https://habr.com/ru/post/1569711/


All Articles