Simple operator overload = in C++

Matt99

I have a problem in my code that does not display an apparent error. I created a Vector and Matrix class. The problem lies when I try to overload the = operator for the Matrix class. For example, if A and B are two matrices, I want the operation B = A to modify B which becomes A. This works for vectors but for matrices, I have a "Segmentation fault" error that I can't get not to solve: it is a problem of memory or prohibited modification but I cannot see.

// My code
#include <iostream>
#include <cmath>

using namespace std;

class Vecteur{
private:
    float *tab;
    int dim;

public:
    void affiche();
    Vecteur(int);
    Vecteur(float*, int);
    ~Vecteur();
    Vecteur(const Vecteur &);
    Vecteur operator=(const Vecteur &);
    Vecteur operator+(const Vecteur &);
    Vecteur operator-(const Vecteur &);
    float & operator[](int);
    Vecteur subvec(int, int);
    int getDimension(); //utile pour la fonction dot
    friend Vecteur operator*(float, const Vecteur &);
    Vecteur(); //Constructeur vide pour la class Matrice
    friend class Matrice;
 };

void Vecteur::affiche(){
    cout << "Le tenseur est de dimension :"<<dim<<endl;
    cout << "Voici le contenu du tenseur :\n";
    for(int i=0;i<dim;i++){
        cout <<tab[i]<<"\n";
    }
}

Vecteur::Vecteur(int taille){
    dim = taille;
    tab = new float[taille];
    for(int i=0;i<dim;i++){
        tab[i] = 0;
    }
}

Vecteur::Vecteur(float *tableau, int taille){
    dim = taille;
    tab = new float[dim];
    for(int i=0;i<dim;i++){
        tab[i] = tableau[i];
    }
}

Vecteur::~Vecteur(){
    delete tab;
}

Vecteur::Vecteur(const Vecteur &a){
    dim = a.dim;
    tab = new float[dim];
    for(int i=0;i<dim;i++){
        tab[i] = a.tab[i];
    }
}

Vecteur Vecteur::operator=(const Vecteur &a){
    if(this != &a){
        this->~Vecteur();
        dim = a.dim;
        tab = new float[dim];
        for(int i=0;i<dim;i++){
            tab[i] = a.tab[i];
        }
    }
    return *this;
}

Vecteur Vecteur::operator+(const Vecteur &a){
    if(dim == a.dim){
        float tab_b[dim];
        for(int i=0;i<dim;i++){
            tab_b[i] = tab[i] + a.tab[i];
        }
        Vecteur b(tab_b, dim);
        return b;
    } else {
        cout <<"Les vecteurs ne sont pas de meme taille.\n";
        float tab_b[1] = {0};
        Vecteur b(tab_b, 1);
        return b;
    }
}     

Vecteur Vecteur::operator-(const Vecteur &a){
    if(dim == a.dim){
        float tab_b[dim];
        for(int i=0;i<dim;i++){
            tab_b[i] = tab[i] - a.tab[i];
        }
        Vecteur b(tab_b, dim);
        return b;
    } else {
        cout <<"Les vecteurs ne sont pas de meme taille.\n";
        float tab_b[1] = {0};
        Vecteur b(tab_b, 1);
        return b;
    }
}    

float & Vecteur::operator[](int i){
    return tab[i];
}

Vecteur Vecteur::subvec(int i, int j){
    float sous_tab[j-i+1];
    for(int k=i;k<j+1;k++){
        sous_tab[k-i]=tab[k];
    }
    Vecteur c(sous_tab, j-i+1);
    return c;
}

int Vecteur::getDimension(){
    return dim;
}

Vecteur operator*(float k, const Vecteur &d){
    int dimension = d.dim;
    float tab_b[dimension];
    for(int i=0;i<dimension;i++){
        tab_b[i] = k * d.tab[i];
    }
    Vecteur b(tab_b, dimension);
    return b;
}

Vecteur::Vecteur(){ }


class Matrice{
    private:
        Vecteur *mat;
        int dims[2];

    public:
        void affiche();
        Matrice();
        Matrice(int, int);
        Matrice(Vecteur);
        Matrice(Vecteur *, int);
        ~Matrice();
        Matrice(const Matrice &M);
        Matrice & operator=(const Matrice &);
        Vecteur & operator[](int);
        Matrice operator+(const Matrice &);
        Matrice operator-(const Matrice &);
        Matrice operator*(const Matrice &);
};

void Matrice::affiche(){
    cout << "La matrice est de dimension "<<dims[0]<<" x "<<dims[1]<<endl;
    cout << "Les coefficients de la matrice sont : \n";
    for(int i=0;i<dims[0];i++){
        for(int j=0;j<dims[1];j++){
            cout <<mat[j][i]<<" ";
            if(j==dims[1]-1){
                cout <<"\n";
            }
        }
    }
}

Matrice::Matrice(int nbLignes, int nbColonnes){
    dims[0] = nbLignes;
    dims[1] = nbColonnes;
    mat = new Vecteur[nbColonnes];
    for(int i=0;i<nbColonnes;i++){
        mat[i] = Vecteur(nbLignes);
    }
}

Matrice::Matrice(Vecteur a){
    int taille = a.getDimension();
    dims[0] = taille;
    dims[1] = taille;
    
    mat = new Vecteur[taille];
    for(int i=0;i<taille;i++){
        mat[i] = Vecteur(taille);
    }
    
    //Puis on modifie les termes diagonaux
    for(int i=0;i<taille;i++){
        mat[i][i] = a[i];
    }
}

Matrice::Matrice(Vecteur *M, int taille){
    dims[0] = M[0].getDimension();
    dims[1] = taille;
    mat = new Vecteur[taille];
    for(int i=0;i<dims[1];i++){
        mat[i] = M[i];
    }
}

Matrice::~Matrice(){
    delete mat;
}

//Constructeur de recopie
Matrice::Matrice(const Matrice &M){
    dims[0] = M.dims[0];
    dims[1] = M.dims[1];
    mat = new Vecteur[dims[1]];
    for(int i=0;i<dims[1];i++){
        mat[i] = M.mat[i];
    }
}

Matrice & Matrice::operator=(const Matrice &M){
   if(this != &M)
   {
        this->~Matrice();
        dims[0] = M.dims[0];
        dims[1] = M.dims[1];
        mat = new Vecteur[dims[1]];
        for(int i=0;i<dims[1];i++){
            mat[i] = Vecteur(dims[0]);
        }
        for(int i=0;i<dims[0];i++){
            for(int j=0;j<dims[1];j++){
                mat[j][i] = M.mat[j][i];
            }        
        }
    }
    return *this;
}

Vecteur & Matrice::operator[](int i){
    return mat[i];
}

Matrice::Matrice(){
    mat = nullptr;
}

int main() {
    float tab_a[] = {1,2,3,4};
    Vecteur a(tab_a, 4);
    Matrice A(a);
    float tab_b[] = {5,6,7,8};
    Vecteur b(tab_b, 4);
    Matrice B(b);
    B.affiche();
    B = A;
    B.affiche(); //Show nothing
}

Thanks

newdeep ji

This smells,

    this->~Matrice();
    dims[0] = M.dims[0];
    dims[1] = M.dims[1];

You deleted the object and are again trying to assign the deleted object.You cannot assign to a deleted object.

It should be noted that,

dims[0] 

is equivalent to

this->dims[0];

You should just remove the line that is calling the destructor and also change the call to delete to delete[] in its destructor.

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

C++ comparison operator overload confusing behavior

how to overload << operator in c++ to use repeatedly?

Which overload does an operator use in C++?

How can I overload the assignment operator in c++

How to do C++ custom structured array subscript operator overload?

how to overload an assignment operator in swift

Overload method with spread operator not recognized

Python: How to overload operator with ast

How to iterate a class that overload the operator[]?

Operator overload "<" declared in Swift class is sometimes not called when used in Objective-C

Propósito del parámetro ficticio en Postfix Operator Overload? c ++

How to concatenate two dictionaries with a += operator overload

Swift - Operator Overload - Multiplicación para CGFloat

SFML: How to overload Packet operator >> with a std::vector?

Custom stream manipulator that passes a character to operator overload

Is there a way to use an overload operator as part of a comparison

C ++ Operator "=" overload - Obtiene todos los valores en el vector en lhs para igualar un valor doble en rhs

Ambiguous overload for ‘operator=’ when trying to invoke the move assignment operator

Ambiguous overload for 'operator==' with own class and std::string_view

is it possible to overload the increment operator (++) to increment by more than 1?

Conditionally providing overload of comparizon operator if template parameter provides it too

How to properly overload the stream operator for printing in an polymorphic class?

Returning const value from arithmetic operator overload with move assignment

Overload -> operator to forward member-access through Proxy

How to overload the arrow dereference operator->() not for solid objects but for pointers

iterator operator overload ++ & - tiene un argumento int pero no se usa

Boost phoenix member function operator fails to compile if function has overload

класс c ++ с 'operator =' и вектором, я не знаю, как его правильно использовать

Ошибка итератора набора C ++: нет совпадения для 'operator + =' в наборе

TOP Lista

CalienteEtiquetas

Archivo