Visualizzazione dei risultati da 1 a 4 su 4
  1. #1

    [C++] Inizializzazione oggetti globale

    Salve a tutti, avrei un problema. dovrei dichiarare un oggetto globalmente di tipo Grid. SUccessivamente, una volta acquisiti determinati parametri, dovrei inizializzare il mio oggetto all'interno del main. In pratica ho una situazione di questo tipo

    codice:
    #include <iostream>
    #include "Grid.h"
    
    Grid grid;
    int dimA, dimB;
    
    int main(int argc, char** argv)
    { 
    
    [codice vario]
    
    grid = new Grid(dimA, dimB)
    }

    solo che ottengo il seguente errore

    no match for ‘operator=’ in ‘grid = (operator new(16u), (<statement>, ((Grid*)<anonymous>)))’
    Grid.h:12: note: candidates are: Grid& Grid:perator=(const Grid&)

    di seguito, il codeice di Grid.cpp e Grid.h




    GRID.CPP

    codice:
    #include "Grid.h"
    #include "Cell.h"
    #include <iostream>
    #include <math.h>
    #include <time.h>
    
    using namespace std;
    
    
    	
    	
    Grid::Grid()
    {
    	  
    	
    	int i, j;
      height = 100;
      width = 100;
     
      // c style memory allocation. more efficient than doing |height| allocations
      linear = (Cell *) malloc( width * height * sizeof(Cell) );
      grid = (Cell **) malloc( height * sizeof(Cell *) );
      for( i = 0; i < height; i++ )
        grid[i] = &linear[i*width];
      for( i = 0; i < height; i++ ) {
        for( j = 0; j < width; j ++ ) {
          setState(i, j, 0);
         
        }
      }
    
    }
    	
    	
    Grid::Grid(const Grid &grid)
    {
    	
    	}
    	
    	 
    Grid::Grid(const int w, const int h)
    {
    	int i, j;
      height = h;
      width = w;
      // c style memory allocation. more efficient than doing |height| allocations
      linear = (Cell *) malloc( width * height * sizeof(Cell) );
      grid = (Cell **) malloc( height * sizeof(Cell *) );
    
      for( i = 0; i < height; i++ )
        grid[i] = &linear[i*width];
      for( i = 0; i < height; i++ ) {
        for( j = 0; j < width; j ++ ) {
          setState(i, j, 0);
         
        }
      }
    }
    
    Grid::~Grid()
    {
    	free(grid);
    	free(linear);
    	
    }
    
    
    int Grid::getHeight()
    {
    	return height;
    }
    	
    	
    void Grid::setHeight(int h)
    {
    	height = h;
    }
    
    
    int Grid::getWidth()
    {
    	return width;
    }
    
    
    void Grid::setWidth(int h)
    {
    	width = h;
    }
    
    
    void Grid::printGrid()
    {
      int i, j;
      for( i = 0; i < height; i++ ) {
        for( j = 0; j < width; j++ ) {
    		
    		if(getState(i,j) == 1)
    			cout<<"X";
    		else
    			cout<<"0";
        }
       cout<<endl;
      }
      
      cout<<endl<<endl<<endl;
    }
    
    
    int Grid::countNeighbor(int i, int j)
    {
    	int counter = 0;
    	if(i >= 0 && i<width && j >=0 &&  j<height)
    	{
    		if(getState(i-1,j+1) == 1)
    			counter++;
    		if(getState(i+1,j+1) == 1)
    			counter++;
    		if(getState(i-1,j-1) == 1)
    			counter++;
    		if(getState(i+1,j-1) == 1)
    			counter++;
    		if(getState(i,j+1) == 1)
    			counter++;
    		if(getState(i,j-1) == 1)
    			counter++;
    		if(getState(i-1,j) == 1)
    			counter++;
    		if(getState(i+1,j) == 1)
    			counter++;
    		
    		}
    		
    		return counter;
    }
    
    
    int Grid::getState(int i, int j)
    {
    	return grid[i][j].alive;
    }
    
    
    void Grid::setState(int i, int j, int state)
    {
    	grid[i][j].alive = state;
    }
    
    
    void Grid::randomizeGrid()
    {
    srand( (unsigned int) time( NULL ));
    for(int i = 0; i<width; i++)
    for(int j = 0; j<height; j++)
    {
    	if(rand()%4 == 0)
    		setState(i,j,1);
    		else
    		setState(i,j,0);
    	}	
    
    }
    
    
    
    void Grid::readGridFromFile(char* fileName)
    {
    	
    }
    
    // col - start column
    // row - start row
    // nCols - number of columns to be processed
    // nRows - number of rows to be processed
    void Grid::doLife(int row, int col, int nRows, int nCols)
    {
    
    	Grid nextGrid(getHeight(), getWidth());
    	int i, j;
    	for( i = row; i < row+nRows; i++ ) 
    		for( j = col; j < col+nCols; j++ ) {
    			int aliveNeigh = countNeighbor(i,j);
    				if( getState(i, j) == 1 )
    					if( aliveNeigh <= 1 || aliveNeigh >= 4 )
    						nextGrid.setState(i, j, 0);
    					else if ( aliveNeigh == 2 || aliveNeigh == 3 )
    						nextGrid.setState(i, j, 1);
    					else
    						nextGrid.setState(i, j, getState(i, j));
    					else
    						if( aliveNeigh == 3 )
    							nextGrid.setState(i, j, 1);
    					else
    						nextGrid.setState(i, j, getState(i, j));	
    	}
    	
    	 for( i = row; i < row+nRows; i++ ) 
        for( j = col; j < col+nCols; j++ ) 
          setState(i, j, nextGrid.getState(i, j));
    	
    
    }
    
    
    void Grid::doAlien(int i, int j, int numRows, int numCols)
    {
    	
    }
    
    
    void Grid::cleanGrid()
    {
    	for(int i = 0; i<height; i++)
    		for(int j = 0; j<width; j++)
    			setState(i,j,0);
    }
    
    
    void Grid::reallocateGrid(int w, int h)
    {
    	free(grid);
    	free(linear);
    
    
    	int i, j;
      height = h;
      width = w;
      // c style memory allocation. more efficient than doing |height| allocations
      linear = (Cell *) malloc( width * height * sizeof(Cell) );
      grid = (Cell **) malloc( height * sizeof(Cell *) );
    
      for( i = 0; i < height; i++ )
        grid[i] = &linear[i*width];
      for( i = 0; i < height; i++ ) {
        for( j = 0; j < width; j ++ ) {
          setState(i, j, 0);
         
        }
      }
    
    	
    	}
    	
    void Grid::reallocateGrid()
    {
    	free(grid);
    	free(linear);
    	
    	
      height = 100;
      width = 100;
      // c style memory allocation. more efficient than doing |height| allocations
      linear = (Cell *) malloc( width * height * sizeof(Cell) );
      grid = (Cell **) malloc( height * sizeof(Cell *) );
    
      for( int i = 0; i < height; i++ )
        grid[i] = &linear[i*width];
      for(int i = 0; i < height; i++ ) {
        for(int j = 0; j < width; j ++ ) {
          setState(i, j, 0);
         
        }
      }
    	}

    GRID.H

    codice:
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <time.h>
    #include "Cell.h"
    
    
    #ifndef GRID_H
    #define GRID_H
    
    class Grid{
    public:
     Cell** grid;
     Cell* linear;
    
     int height;
     int width;
     
    
    
     Grid();
     Grid(const Grid &grid);
     Grid(const int w, const int h);                
     ~Grid();
     int getHeight();
     void setHeight(int h);
     int getWidth();
     void setWidth(int h);
     void printGrid();
     int countNeighbor(int i, int j);
     int getState(int i, int j);
     void setState(int i, int j, int state);
     void randomizeGrid();
     void readGridFromFile(char* fileName);
     void doLife(int i, int j, int numRows, int numCols);
     void doAlien(int i, int j, int numRows, int numCols);
     void cleanGrid();
     void reallocateGrid(int w, int h);
     void reallocateGrid();
    
    };
    #endif
    Immagini allegate Immagini allegate

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Il Grid globale dev'essere un pointer.
    This code and information is provided "as is" without warranty of any kind, either expressed
    or implied, including but not limited to the implied warranties of merchantability and/or
    fitness for a particular purpose.

  3. #3
    La variabile globale grid è un oggetto (non un puntatore), pertanto viene costruito automaticamente all'avvio del programma con il suo costruttore di default. Non puoi fare quell'assegnamento dato che significherebbe assegnare un puntatore ad un oggetto.
    Se tutti i dati per inizializzare l'oggetto sono noti prima ancora che parta il main, semplicemente usa un costruttore parametrizzato al posto del costruttore di default.
    In caso contrario, dichiara grid come puntatore (sarebbe anche meglio uno smart pointer come std::auto_ptr o boost::scoped_ptr) e usa new come stai già facendo; se non usi uno smart pointer ricordati la delete alla fine.
    Esiste anche una terza via: usi il costruttore di default e poi l'operatore di assegnamento da un rvalue temporaneo:
    codice:
    grid = Grid(dimA, dimB)
    ma "sprechi" la costruzione con il costruttore di default.
    Noto tra l'altro che la tua classe non definisce un operatore di assegnamento e lascia il costruttore di copie vuoto: questa è una condizione potenzialmente pericolosa, o li definisci correttamente (dato che quelli di default nel tuo caso non vanno bene visto che stai gestendo della memoria), altrimenti ti conviene bloccarli, dichiarandoli come private e non implementandoli, in modo da evitare che il compilatore generi quelli di default.
    Amaro C++, il gusto pieno dell'undefined behavior.

  4. #4
    capito... grazie mille... spero di risolvere il problema.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.