Унаследованные проблемы класса

У меня есть следующий код, и я не знаю, как решить функцию mult. компилятор отправил мне сообщение, что не может объявить параметр "a" типом "Matriz"

Я должен использовать именно тот код, который находится в основном

Сообщение не может объявить параметр "a" типом "Matriz".

enter code here
#include <iostream>
#include <iomanip>
using namespace std;
// Base
class IMatriz {
   int **m;
   int numRows;
   int numColumns;
   public:
      IMatriz(){
         numRows = 0;
         numColumns = 0;
         m = NULL;
      }   
      IMatriz(int r, int c) {
         numRows = r;
         numColumns = c;
         m = new int* [numRows];
         for(int i=0; i < numRows; i++)
            m[i] = new int [numColumns];
      }
      virtual void setSize(int r, int c) = 0;
      virtual void setValue(int row, int col, int val) = 0;
      virtual int getValue(int row, int col) = 0;
      virtual int getNumRows() = 0;
      virtual int getNumColumns() = 0;
      virtual void mult(IMatriz a, IMatriz b) = 0;
      virtual void print(void) = 0;
};
// Inherited
class Matriz : public IMatriz {
   protected:
      int **m;
      int numRows;
      int numColumns;   
   public:
      Matriz()
     :  IMatriz()
     {
     }

  Matriz(int r, int c)
     :  IMatriz(r, c)
     {
        numRows = r;
        numColumns = c;
        m = new int* [numRows];

        for(int i=0; i < numRows; i++)
           m[i] = new int [numColumns];
     }

  void setSize(int r, int c);
  void setValue(int row, int col, int val);
  int getValue(int row, int col);
  int getNumRows();
  int getNumColumns();
  void mult(Matriz a, Matriz b);
  void print();
};
// Functions
void Matriz::setSize(int r, int c) {  
   numRows = r;
   numColumns = c;
}
void Matriz::setValue(int row, int col, int val) {    
   m[row][col] = val;
}
int Matriz::getValue(int row, int col) {
   return m[row][col];
}
int Matriz::getNumRows() {
   return numRows;
}
int Matriz::getNumColumns() {
   return numColumns;
}
**void Matriz::mult(Matriz a, Matriz b) {**
//   m.setSize( a.getNumRows(), b.getNumColumns() );
//   for (int rows = 0; rows < numRows; rows ++)
//      for (int cols = 0; cols < numColumns; cols ++)
//         m[rows][cols] = 0;
//   for (int rows = 0; rows < a.getNumRows(); rows ++)
//      for (int cols = 0; cols < b.getNumColumns(); cols ++)
//         for (int auxl = 0; auxl < a.getNumColumns(); auxl ++)
//            m[rows][cols] += (a[rows][auxl] * b[auxl][cols]);
   return;
}
void Matriz::print() {
   for (int rows  = 0; rows < numRows; rows ++)
   {
      for (int cols = 0; cols < numColumns; cols ++)
         cout << m[rows][cols] << " ";

      cout << endl;
   }
}
// Principal
int main() {
   Matriz m;
   Matriz a(3, 2);
   Matriz b(2, 3);
   a.setValue(0,0,7);
   a.setValue(0, 0, 7);
   a.setValue(1, 0, 1);
   a.setValue(2, 0, 8);
   a.setValue(0, 1, 2);
   a.setValue(1, 1, 5);
   a.setValue(2, 1, 6);
   b.setValue(0, 0, 2);
   b.setValue(1, 0, 3);
   b.setValue(0, 1, 5);
   b.setValue(1, 1, 4);
   b.setValue(0, 2, 8);
   b.setValue(1, 2, 9);
   a.print();
   b.print();
//   m.mult(a,b);
//   m.print();
   return 0;
}

person KarlaE    schedule 22.10.2013    source источник
comment
Как насчет того, чтобы включить полное сообщение о компиляции и выделить строку, в которой возникла проблема?   -  person John3136    schedule 22.10.2013
comment
@BergQuester Кажется, мы можем сделать вывод и по его псевдониму :)   -  person Terry Li    schedule 22.10.2013
comment
Вы выделяете память внутри конструкторов, но никогда не освобождаете ее внутри деструктора, не говоря уже о соблюдении правила трех или правила нуля.   -  person chris    schedule 22.10.2013


Ответы (3)


Сделал некоторые изменения в вашем коде. Пожалуйста, найдите фиксированный код ниже -

#include <iostream>
#include <iomanip>
using namespace std;
// Base

class IMatriz;

class IMatriz {
    int **m;
    int numRows;
    int numColumns;
public:
    IMatriz(){
        numRows = 0;
        numColumns = 0;
        m = NULL;
    }
    IMatriz(int r, int c) {
        numRows = r;
        numColumns = c;
        m = new int* [numRows];
        for(int i=0; i < numRows; i++)
            m[i] = new int [numColumns];
    }
    virtual void setSize(int r, int c) = 0;
    virtual void setValue(int row, int col, int val) = 0;
    virtual int getValue(int row, int col) = 0;
    virtual int getNumRows() = 0;
    virtual int getNumColumns() = 0;
    virtual void mult(IMatriz &a, IMatriz &b) = 0;
    virtual void print(void) = 0;
};
// Inherited
class Matriz : public IMatriz {
protected:
    int **m;
    int numRows;
    int numColumns;
public:
    Matriz()
    :  IMatriz()
    {
    }

    Matriz(int r, int c)
    :  IMatriz(r, c)
    {
        numRows = r;
        numColumns = c;
        m = new int* [numRows];

        for(int i=0; i < numRows; i++)
            m[i] = new int [numColumns];
    }

    void setSize(int r, int c);
    void setValue(int row, int col, int val);
    int getValue(int row, int col);
    int getNumRows();
    int getNumColumns();
    void mult(IMatriz &a, IMatriz &b);
    void print();
};
// Functions
void Matriz::setSize(int r, int c) {
    numRows = r;
    numColumns = c;
}
void Matriz::setValue(int row, int col, int val) {
    m[row][col] = val;
}
int Matriz::getValue(int row, int col) {
    return m[row][col];
}
int Matriz::getNumRows() {
    return numRows;
}
int Matriz::getNumColumns() {
    return numColumns;
}
void Matriz::mult(IMatriz &a, IMatriz &b) {
    //   m.setSize( a.getNumRows(), b.getNumColumns() );
    //   for (int rows = 0; rows < numRows; rows ++)
    //      for (int cols = 0; cols < numColumns; cols ++)
    //         m[rows][cols] = 0;
    //   for (int rows = 0; rows < a.getNumRows(); rows ++)
    //      for (int cols = 0; cols < b.getNumColumns(); cols ++)
    //         for (int auxl = 0; auxl < a.getNumColumns(); auxl ++)
    //            m[rows][cols] += (a[rows][auxl] * b[auxl][cols]);
    return;
}
void Matriz::print() {
    for (int rows  = 0; rows < numRows; rows ++)
    {
        for (int cols = 0; cols < numColumns; cols ++)
            cout << m[rows][cols] << " ";

        cout << endl;
    }
}
// Principal
int main(int argc, const char * argv[]) {
    Matriz m;
    Matriz a(3, 2);
    Matriz b(2, 3);
    a.setValue(0,0,7);
    a.setValue(0, 0, 7);
    a.setValue(1, 0, 1);
    a.setValue(2, 0, 8);
    a.setValue(0, 1, 2);
    a.setValue(1, 1, 5);
    a.setValue(2, 1, 6);
    b.setValue(0, 0, 2);
    b.setValue(1, 0, 3);
    b.setValue(0, 1, 5);
    b.setValue(1, 1, 4);
    b.setValue(0, 2, 8);
    b.setValue(1, 2, 9);
    a.print();
    b.print();
    //   m.mult(a,b);
    //   m.print();
    return 0;
}

Это вывод, который я получаю на консоли xcode -

7 2 
1 5 
8 6 
2 5 8 
3 4 9 
person Ashok    schedule 22.10.2013
comment
да у меня то же самое, но приходится запускать функцию мульт все есть коментарии - person KarlaE; 22.10.2013
comment
что-то вроде этого void Matriz::mult(IMatriz &a, IMatriz &b) { this-›setSize(a.getNumRows(), b.getNumColumns()); for (int rows = 0; rows ‹ numRows; rows ++) for (int cols = 0; cols ‹ numColumns; cols ++) m[rows][cols] = 0; for (int rows = 0; rows ‹ a.getNumRows(); rows ++) for (int cols = 0; cols ‹ b.getNumColumns(); cols ++) for (int auxl = 0; auxl ‹ a.getNumColumns (); auxl ++) m[rows][cols] += (a.getValue(rows,auxl) * b.getValue(auxl,cols)); возврат; } - person KarlaE; 22.10.2013
comment
Matriz m; вызывает конструктор по умолчанию, но int **m; имеет значение NULL, поэтому происходит сбой внутри функции mult, пытающейся получить доступ к этому объекту-члену. - person Ashok; 22.10.2013
comment
да, вот почему я поставил это-›setSize(a.getNumRows(), b.getNumColumns()); на мультифункции - person KarlaE; 22.10.2013
comment
В этом случае вам нужно динамически выделить память для int **m; переменная снова внутри функции setSize. m = new int* [numRows]; for(int i=0; i < numRows; i++) m[i] = new int [numColumns]; - person Ashok; 22.10.2013
comment
ХОРОШО. Однако в своем волнении не допускайте утечки памяти и не забудьте delete ранее выделенную память на m в зависимости от вашей реализации/требований;) - person Ashok; 22.10.2013
comment
Привет, мне нужна помощь - person KarlaE; 18.11.2013

Вы забыли нового оператора (или Malloc)

Matriz a = new Matriz(3, 2);
person lordkain    schedule 22.10.2013
comment
законно вызывать конструктор, как это делал OP - person lolando; 22.10.2013
comment
ты хотел сказать Matriz* a = new Matriz(3, 2)? - person Sam; 22.10.2013

Первая проблема заключается в том, что вы не можете создать экземпляр абстрактного объекта, такого как IMatriz, вам нужно изменить его на IMatriz* a или IMatriz& a в следующем объявлении функции.

virtual void mult(IMatriz a, IMatriz b) = 0;

Во-вторых, приведенная выше чистая виртуальная функция не переопределяется классом Matriz, что делает класс Matriz по-прежнему абстрактным классом. Потому что в производном классе вы объявляете его как void mult(Matriz a, Matriz b); , другую сигнатуру функции, как в базовом классе.

Решение состоит в том, чтобы изменить void mult(Matriz a, Matriz b); на void mult(IMatriz* a, IMatriz* b) как в базовом, так и в производном классе и вызвать его с помощью указателей.

person Zac Wrangler    schedule 22.10.2013
comment
привет у меня такая же проблема не могу объявить параметр a' to be of type IMatriz' - person KarlaE; 22.10.2013
comment
@cplusplus отредактировано, вы не можете использовать абстрактный класс в качестве типов параметров. - person Zac Wrangler; 22.10.2013