Come funziona std :: string sovraccaricare l'operatore di assegnazione?
-
21-09-2019 - |
Domanda
class mystring {
private:
string s;
public:
mystring(string ss) {
cout << "mystring : mystring() : " + s <<endl;
s = ss;
}
/*! mystring& operator=(const string ss) {
cout << "mystring : mystring& operator=(string) : " + s <<endl;
s = ss;
//! return this;
return (mystring&)this; // why COMPILE ERROR
} */
mystring operator=(const string ss) {
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this;
}
mystring operator=(const char ss[]) {
cout << "mystring : mystring operator=(char[]) : " << ss <<endl;
s = ss;
return *this;
}
};
mystring str1 = "abc"; // why COMPILE ERROR
mystring *str2 = new mystring("bcd");
Così i questiones sono
-
come fare una corretta mystring & opeartor = sovraccarico? Cioè, come ho potuto restituire un riferimento piuttosto che un puntatore? (Potremmo tranfer tra riferimento e puntatore in C ++?)
-
come fare una corretta operatore di MyString = sovraccarico? Ho pensato che il codice sorgente avrebbe funzionato bene, ma si scopre ancora non riuscivo assegnare const char [] per myString come se io non sovraccaricare l'operatore = .
Grazie.
Soluzione
Quello che ti serve è un costruttore di 'conversione' che prende un const char*
mystring( char const* ss) {
cout << "mystring : mystring(char*) ctor : " << ss <<endl;
s = ss;
}
La linea si sta avendo un problema con:
mystring str1 = "abc"; // why COMPILE ERROR
Non è davvero un incarico - è un inizializzatore
.Altri suggerimenti
mystring& operator=(const string &ss)
{
cout << "mystring : mystring operator=(string) : " + s <<endl;
s = ss;
return *this; // return the reference to LHS object.
}
Come altri hanno sottolineato, "string"
ha const char *
tipo e si dovrebbe sovraccaricare operatore di assegnazione per esso.
mystring& operator=(const char * s);
Per ottenere un riferimento da un *this
puntatore è bastano, non c'è bisogno di lanciare qualsiasi cosa.
mystring& operator=(const string& ss) {
cout << "mystring : mystring operator=(string) : " << s << endl;
s = ss;
return *this;
}
mystring& operator=(const char* const pStr) {
cout << "mystring : mystring operator=(zzzz) : " << pStr << endl;
s = pStr;
return *this;
}
- ho aggiunto 'e' sulle tue corde in modo che restituisce un riferimento a 'questo' e non una copia di esso (è buona norma farlo per il parametro di ingresso troppo come si sta allora non fare un uneccessarily copia della stringa di input),
- ho scambiato un '+' a '<<' in linea 2
- e ho modificato l'array a un const char const * Puntatore