简体   繁体   English

需要帮助使操作员超负荷+

[英]need help to overload the operator +

so i want to overload operator + (C++) in my class matrices to use this instruction m1 = m2 + m3 所以我想在我的类矩阵中重载运算符+(C ++)以使用此指令m1 = m2 + m3

knowing that i have already overload th operator = but it crashes at execution here is my code class matrices: 知道我已经重载了operator =,但是执行时崩溃,这是我的代码类矩阵:

#include "../include/matrices.h"
#include <iostream>
using namespace std;

class matrices
{
    public:
        int taille;
        int **tab;
    public:
        matrices();
        matrices(int);
        matrices(matrices &);
        virtual ~matrices();
        void setTaille(int);
        int getTaille();
        void setVal(int, int, int);
        int getVal(int, int);
        friend istream& operator >> (istream&, matrices& ); //surcharge de l'opérateur >>
        friend ostream& operator << (ostream&, const matrices& ); //surcharge de l'opérateur <<
        //void operator=(matrices&);
        matrices& operator=(matrices& );
        //friend matrices& operator+(matrices , matrices );
        friend matrices& operator+(matrices&, matrices&);
        friend matrices operator-(matrices);
        friend matrices operator*(matrices);
};

matrices::~matrices()
{
    //dtor
}

matrices::matrices()
{
    taille = 2;
    this->tab = new int*[taille];
    for(int i=0; i<taille; i++)
        this ->tab[i] = new int[taille];
}

matrices::matrices(int n)
{
    taille = n;
    this->tab = new int*[taille];
    for(int i=0; i<taille; i++)
        this->tab[i] = new int[taille];
}

matrices::matrices(matrices & m1)
{
    (*this).taille = m1.taille;
    tab = new int*[(*this).taille];
    for(int i=0; i<(*this).taille; i++)
        for(int j=0; j<(*this).taille; j++)
            this->tab[i][j] = m1.tab[i][j];
}

void matrices::setTaille(int n)
{
    (*this).taille = n;
}

int matrices::getTaille()
{
    return (*this).taille;
}

void matrices::setVal(int val, int n, int m)
{
    this->tab[n][m] = val;
}

int matrices::getVal(int n, int m)
{
    return this->tab[n][m];
}

istream& operator >> (istream& flux, matrices& m1)
{
    for(int i=0; i<m1.taille; i++)
    {
        for(int j=0; j<m1.taille; j++)
        {
            flux >> m1.tab[i][j];
        }
    }
    return (flux);
}

ostream& operator << (ostream& flux, const matrices& m1)
{
    for(int i=0; i<m1.taille; i++)
    {
        for(int j=0; j<m1.taille; j++)
        {
            flux << m1.tab[i][j];
            cout << "\t" ;
        }
        cout << "\n" << endl;
    }
    return (flux);
}

matrices& matrices::operator=(matrices& m1)
{
    delete this->tab;
    (*this).taille = m1.taille;
    this->tab = new int*[m1.taille];
    for(int i=0; i<m1.taille; i++)
        this->tab[i] = new int[m1.taille];

    for(int i=0; i<m1.taille; i++)
    {
        for(int j=0; j<m1.taille; j++)
        {
            this->tab[i][j] = m1.tab[i][j];
        }
    }
    return (*this);
}

matrices& operator+(matrices&  m1, matrices&  m2)
{
    matrices mtmp;
    mtmp.taille = m1.taille;
    mtmp.tab = new int*[mtmp.taille];
    for(int i=0; i<mtmp.taille; i++)
        mtmp.tab[i] = new int[mtmp.taille];

        if(m2.taille == m1.taille)
        {
            for(int i=0; i<mtmp.taille; i++)
            {
                for(int j=0; j<mtmp.taille; j++)
                {
                    mtmp.tab[i][j] = m1.tab[i][j] + m2.tab[i][j];
                }
            }
        }
        return mtmp;
}

and this is my main fonction 这是我的主要功能

#include <iostream>
#include "include/matrices.h"
#include<stdlib.h>
#include<stdio.h>
#include<string>

using namespace std;

int main()
{
    matrices m1,m2,m3;
    cin >> m1;
    cin >> m3;
    m2 = m1;
    cout << "=================================" << endl;
    cout << "==== Affichage de la matrice ====" << endl;
    cout << "=================================" << endl;
    cout << m2;
    getchar();

    cout << "==================================" << endl;
    cout << "==== sommation des 2 matrices ====" << endl;
    cout << "==================================" << endl;
    m3 = m1 + m2;
    cout << "==================================" << endl;
    cout << "==== matrice m3 matrices est: ====" << endl;
    cout << "==================================" << endl;
    cout << m3;
}

thanks for your help 谢谢你的帮助

You must be either using a compiler that does not give you a warning about this, or are ignoring the warning: 您必须使用没有为此警告的编译器,或者正在忽略该警告:

matrices& operator+(matrices&  m1, matrices&  m2)
{
    matrices mtmp;
    ...
    return mtmp;
}

The code is a big problem: you are attempting to return a reference to an automatic variable. 代码是个大问题:您正在尝试返回对自动变量的引用。 By the time you attempt to use the reference, the object no longer exists. 在您尝试使用引用时,该对象已不存在。

You should declare your overload this way: 您应该这样声明过载:

matrices operator+(const matrices&  m1, const matrices&  m2)
{
    matrices mtmp;
    ...
    return mtmp;
}

Which will also require you to change your friend declaration: 这还需要您更改朋友声明:

friend matrices operator+(const matrices&, const matrices&);

That way you are returning a copy (since you aren't changing m1 and m2 , you should declare their references as const ). 这样,您将返回一个副本 (因为您没有更改m1m2 ,因此应将它们的引用声明为const )。

Additionally, you should look into the copy-swap idiom for your copy-assignment operator as doing something like m1 = m1 would cause a crash in your current code. 另外,您应该查看拷贝分配操作符的拷贝交换惯用法,因为执行类似m1 = m1会导致当前代码崩溃。 As a corollary to this point: you do not declare a copy-constructor, so when you do something like matricies m2 = m1 , it is doing a shallow copy (the default implementation of the copy-constructor). 推论到这一点:您没有声明一个复制构造函数,因此当您执行matricies m2 = m1 ,它正在执行浅表复制(复制构造函数的默认实现)。 So m2 's pointers are pointing to the data in m1 . 因此, m2的指针指向m1的数据。 When you destruct m1 , m2 contains dangling pointers ... which will cause a heap corruption (deleting already deleted memory). 销毁m1m2包含悬空的指针...这将导致堆损坏(删除已删除的内存)。

A lot of your memory issues (and they are many) go away simply by switching to std::vector or std::array (depending on how you want to define your class) instead of trying to manage the memory yourself. 只需切换到std::vectorstd::array (取决于您要如何定义类),就可以解决很多内存问题(很多),而不必自己管理内存。 A simple (incomplete) example: http://ideone.com/VVqvGy 一个简单的(不完整的)示例: http : //ideone.com/VVqvGy

There are quite a few problems with your class. 您的课程有很多问题。

  1. You dynamically allocate memory in the constructor, but you don't free it in the destructor. 您可以在构造函数中动态分配内存,但不能在析构函数中释放内存。 This is a memory leak. 这是内存泄漏。
  2. In operator=, you free memory that you allocated with new[] with delete (notice the lack of[]): This is undefined behavior, and does random stuff. 在operator =中,使用delete释放通过new[]分配的内存(注意缺少[]):这是未定义的行为,并且是随机的。 You should also delete all dynamically allocated memory, not just the 'top level' - the same way that you allocate it in a loop in the constructor, you should free it in a loop, and use delete[] . 您还应该删除所有动态分配的内存,而不仅仅是“顶层”-与在构造函数中循环分配内存的方式相同,还应在循环中释放它,并使用delete[]
  3. Your setTaille method is pointless: It will only destroy your data, lead to memory leaks and inconsistency in your data. 您的setTaille方法是毫无意义的:它只会破坏您的数据,导致内存泄漏和数据不一致。 It should be either completely reworked, to reallocate and copy the contents of the current matrix to allow the size to be set, or removed altogether. 应该彻底修改,重新分配和复制当前矩阵的内容以设置大小,或者完全删除它。 (I can honestly not imagine a use case for it) (老实说,我无法想象用例)
  4. in operator+ , you should check that the size of the matrices are the same, before performing any allocations. operator+ ,执行任何分配之前,应检查矩阵的大小是否相同。 You should make a decision what should the result of adding non-compatible matrices be (it's a tough choice). 您应该决定添加不兼容矩阵的结果是什么(这是一个艰难的选择)。

The error in your code most probably comes from error number 2. 您的代码中的错误很可能来自错误编号2。

EDIT: I spotted another problem that I overlooked: In your matrices& operator+ function, you return a reference to a auto variable (that is, memory on the stack). 编辑:我发现了另一个我忽略的问题:在您的matrices& operator+函数中,您返回了对自动变量(即堆栈上的内存)的引用。 This is illegal: The moment that you leave the function, this memory becomes garbage. 这是非法的:离开函数的那一刻,该内存就变成了垃圾。 You most probably want to return a copy of the constructed matrix(Use matrices operator+ 您最有可能希望返回构造的矩阵的副本(使用matrices operator+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM