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

    [C++] Domanda sull'operatore di assegnamento (assegnazione)

    Ciao a tutti, ho una domanda da chiedervi, sono nuovo della programmazione in C++ (e anche in altri linguaggi), ultimamente mentre studiavo mi è sorto questo dubbio:

    Perché l'operatore di assegnamento restituisce un indirizzo?

    codice:
    class x{
    int a;
    int b;
    X& operator=(const X &);
    };
    //...
    
    X& X::operator=(const X & o){
    a=o.a;
    b=o.b;
    return *this;
    }
    non ho dubbi sulla validità ma vorrei capire perchè è corretto in questo modo, anche se io l'ho sempre scritto cosi:

    codice:
    class x{
    int a;
    int b;
    X operator=(const X &);
    };
    //...
    
    X X::operator=(const X & o){
    a=o.a;
    b=o.b;
    return *this;
    }
    e ha sempre funzionato.
    Ultima modifica di giuseppe96; 16-01-2017 a 22:15

  2. #2
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Il modo 1 non invoca il costruttore di copia, mentre il secondo lo fa.
    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
    Quindi posso utilizzare entrambi? qual'è meglio?

  4. #4
    Utente di HTML.it L'avatar di shodan
    Registrato dal
    Jun 2001
    Messaggi
    2,381
    Usa il modo 1. Il modo 2 fa un'operazione in più per niente.
    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.

  5. #5
    okok grazie mille!!

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 © 2025 vBulletin Solutions, Inc. All rights reserved.