Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > Разбор ошибок.Перегрузка операторов


Автор: lisica198808 18.5.2014, 11:08
Ну не могу самостоятельно разобрать свои ошибки.Они по большей части повторяются. Помогите пожалуйста.

ошибки следующие:
14  `Matrica Matrica::operator<(Matrica&, Matrica&)' must take exactly one argument 
 In function `Matrica operator<(Matrica&, Matrica)': 
58 no match for 'operator=' in 'rez = P1->Matrica::stroka' 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp:15 candidates are: Matrica Matrica::operator=(Matrica&) 
59  no match for 'operator=' in 'rez = P2.Matrica::stroka' 
 note :15 candidates are: Matrica Matrica::operator=(Matrica&) 
In member function `Matrica Matrica::operator=(Matrica&)': 
63  no matching function for call to `Matrica::Matrica(int&)' 
 noteD:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp :6 candidates are: Matrica::Matrica(const Matrica&) 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp:6                 Matrica::Matrica() 
  In function `int main()':  
92  no match for 'operator=' in 'V = operator<(Matrica&, Matrica)(M2)' 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûê
è\21.cpp:63 candidates are: Matrica Matrica::operator=(Matrica&) 



Задание:V=М1< М2 – из М1 и М2 выбрать строку с наименьшей суммой элементов. М1,М2  матрицы. V  - массив
Код

#include<iostream>/*zagolovochnij fajl s klassami, funktsijami i peremennimi dlja organizacii vvoda-vivoda v jazike programmirovaniya C++*/
/*#include <stdlib.h>*/
using namespace std;/*ob'javlenie prostranstva imen  std.*/

class Matrica
     { float *x;  float *a;
       public:float sum, min; int stroka;int k;int n,m;
              Matrica(); 
              void vvod();
              void vivod(); 
              void min_sum_el();
              void vivod_stroka();
              void ww();
              Matrica  operator< (Matrica& ob1, Matrica& ob2);
              Matrica  operator=(Matrica& ob2);
              ~Matrica(){delete[]x; puts("rabotal destryktor\n");}                
     };
     
  Matrica::Matrica()
  {/*printf("\nvvedite razmernost n*m: ");*/
     scanf("%d %d",&n,&m);
     puts("\nrabotal konstruktor matrici\n");    
    } 
 //==============================================//   
 void Matrica:: vvod()    
      {x = new float [n*m]; 
      for(int i = 0; i < n; i++)
      for(int j = 0; j < m; j++)
      *(x + i * m + j) = rand() % 101 - 50;
      }
//==============================================//
 void Matrica::vivod()/*vivodit matrici na ekran*/
    {printf("\nmatrica:\n"); 
     for(int i = 0; i < n; i++)
     {for(int j = 0; j < m; j++)
      cout<<*(x + i * m + j)<< " ";
      cout << "\n";
     }  
    }
//==============================================//    
 void Matrica::min_sum_el()
  {min = 1000;/*prinimayem za minimum samoye bolshoye chislo tipa  1000*/
   for(int i = 0; i < n; i++)/*idem po strokam*/
   {sum = 0;/*snachala summa v stroke=0*/
    for(int j = 0;  j < m; j++)/*idem po stroke*/
       sum+= *(x + i * m + j);/*summiruyem yeye elementy*/
        if (sum < min) 
        {min = sum; stroka = i + 1;}/*esli summa v dannoy stroke menshe chem predydushchiy minimum to eto minimum i zapomnim nomer stroki*/
   }
  }
 //==============================================//      
  void Matrica::vivod_stroka()
  {printf("Minimalnaya summa= %3.2f v stroke %d ",min, stroka); printf("\n");}
   //==============================================//  
  
Matrica  operator<(Matrica& P1, Matrica P2)  
   {Matrica rez; 
   if (P1.stroka < P1.stroka) rez = P1.stroka;
    else rez = P2.stroka;
       return rez;   }
  //==============================================//         
Matrica Matrica::operator=(Matrica& P1)
{Matrica rez(P1.n);
for(int i = 0; i < n; i++)
*(a + i * m) = *(P1.x + i*P1.m);
return * this;
}

  //==============================================//  
void Matrica::ww()
{for(int i = 0; i < n; i++)
      cout<<*(a + i)<< " ";
      cout << "\n";
}                

int main()
{Matrica M1;
 M1.vvod();
 M1.vivod();
 M1.min_sum_el();
 M1.vivod_stroka();
 system("pause");
 
 Matrica M2;
 M2.vvod();
 M2.vivod();
 M2.min_sum_el();
 M2.vivod_stroka();
 system("pause");
 
 Matrica V;
 V = M1 < M2;
 V.ww();
 system("pause");
    }


Автор: Guinness 19.5.2014, 07:37
Цитата(lisica198808 @  18.5.2014,  12:08 Найти цитируемый пост)
14  `Matrica Matrica::operator<(Matrica&, Matrica&)' must take exactly one argument 
 In function `Matrica operator<(Matrica&, Matrica)': 

Здесь компилятор говорит, что данная функция должна принимать только один параметр. Т.к. функция перегрузки оператора является членом класса, то первая матрица будет передаваться неявно в виде указателя this, а вторая уже через входной параметр. Хотя, судя по коду, будет достаточно в объявлении класса написать:
Код

class Matrica
{
    ...
    friend Matrica  operator< (Matrica& ob1, Matrica& ob2);
    ...
};

Т.к. видимо это подрузумевалось изначально.
Цитата(lisica198808 @  18.5.2014,  12:08 Найти цитируемый пост)
58 no match for 'operator=' in 'rez = P1->Matrica::stroka' 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp:15 candidates are: Matrica Matrica::operator=(Matrica&) 
59  no match for 'operator=' in 'rez = P2.Matrica::stroka' 
 note :15 candidates are: Matrica Matrica::operator=(Matrica&) 

Здесь компилятор говорит, что не может найти соответствующий operator=. Действительно, там зачем-то к объекту Matrica приравнивается int(член Matrica.stroka).
Цитата(lisica198808 @  18.5.2014,  12:08 Найти цитируемый пост)
63  no matching function for call to `Matrica::Matrica(int&)' 
 noteD:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp :6 candidates are: Matrica::Matrica(const Matrica&) 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp:6                 Matrica::Matrica() 

Здесь компилятор сообщает, что не может найти конструктор вида Matrica::Matrica(int&). Т.е. было бы неплохо создать такой для данного класса или использовать предложенные компилятор.
Цитата(lisica198808 @  18.5.2014,  12:08 Найти цитируемый пост)
92  no match for 'operator=' in 'V = operator<(Matrica&, Matrica)(M2)' 
 note D:\Ó×ÅÁÀ\àëãîðèòìè÷åñêèå ÿçûêè\21.cpp:63 candidates are: Matrica Matrica::operator=(Matrica&) 

После исправления первой ошибки, эта должна автоматом исчезнуть.
ЗЫ если не знаешь английского, достаточно было бы в гугл транслейт всё это запихнуть. Ошибки вроде бы понятные.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)